2015-02-05 4 views
1

시스템 로그에 여러 로그 메시지를 쓸 테스트 스텁이 있습니다.python은 로그 파일을 모니터링하지 않습니다

그러나이 시스템 로그는 다른 많은 응용 프로그램에서도 업데이트됩니다. 따라서 기본적으로 적절한 로그 메시지 만 얻으려면 tail -f system.log | grep "application name"을 사용하고 싶습니다.

내가 dbaez 발전기 트릭보고 있었다, 나는 내 __main__()에, 그래서 모두 http://www.dabeaz.com/generators/follow.pyhttp://www.dabeaz.com/generators/apachelog.py

을 결합하는 시도하고,이 같은 뭔가를 :

try: 
    dosomeprocessing()  #outputs stuff to the log file 

그리고 dosomeprocessing 내

(), 루프를 실행하고 각 루프에 대해 응용 프로그램에 의해 발생하는 새로운 로그 메시지가 있는지 반드시 확인하고, 반드시 인쇄하지는 않지만 일부 유효성 검사를 수행하기 위해 어딘가에 저장합니다. 다른 gobblygook의 많은뿐만 아니라

Feb 4 12:55:27 Someprocessname.py I2G(JV)-300[20448]: [ID 702911 local2.error] [MSG-70047] xxxxxxxxxxxxxxxxxxxxxxx 
Feb 4 12:55:27 Someprocessname.py I2G(JV)-300[20448]: [ID 702911 local2.error] [MSG-70055] xxxxxxxxxxxxxxxxxxxxxxx 

:

logfile = open("/var/adm/messages","r") 
    loglines = follow(logfile) 
    logpats = r'I2G(JV)' 
    logpat = re.compile(logpats) 
    groups = (logpat.match(line) for line in loglines) 
    for g in groups: 
     if g: 
      print g.groups() 

로그는 같이 보입니다.

는 지금, 그것은 그룹 g의에 갇혀됩니다 :

나는 파이썬 및 비동기 프로그래밍 비교적 새로운입니다. 이상적으로, 나는 꼬리가 메인 프로세스와 평행하게 돌아가고 각 루프로 새로운 데이터를 읽을 수 있기를 바란다.

자세한 정보를 추가해야하는지 알려주세요.

+0

로그 파일 회전나요 : 여기

은 예입니다? 'follow.py'는'messages'의 이름을'messages.1'로 바꾸는 로거를 처리하지 않고 추가 로그를위한 새로운 파일을 생성합니다. – tdelaney

+0

거의 회전하지 않으며 파일 이름은 동일하게 유지됩니다. – roymustang86

답변

4

로그 파일의 변경 사항을 모니터링하려면 watchdog 또는 pyinotify을 사용하는 것이 좋습니다.

또한 마지막으로 읽은 위치를 기억해 두는 것이 좋습니다. IN_MODIFY 알림을 받으면 마지막 위치에서 파일 끝까지 읽고 루프를 다시 적용 할 수 있습니다. 또한, 파일이 잘린 경우 파일의 크기보다 크면 마지막 위치를 0으로 재설정하십시오.

import pyinotify 
import re 
import os 


wm = pyinotify.WatchManager() 
mask = pyinotify.IN_MODIFY 


class EventHandler (pyinotify.ProcessEvent): 

    def __init__(self, file_path, *args, **kwargs): 
     super(EventHandler, self).__init__(*args, **kwargs) 
     self.file_path = file_path 
     self._last_position = 0 
     logpats = r'I2G\(JV\)' 
     self._logpat = re.compile(logpats) 

    def process_IN_MODIFY(self, event): 
     print "File changed: ", event.pathname 
     if self._last_position > os.path.getsize(self.file_path): 
      self._last_position = 0 
     with open(self.file_path) as f: 
      f.seek(self._last_position) 
      loglines = f.readlines() 
      self._last_position = f.tell() 
      groups = (self._logpat.search(line.strip()) for line in loglines) 
      for g in groups: 
       if g: 
        print g.string 


handler = EventHandler('some_log.log') 
notifier = pyinotify.Notifier(wm, handler) 

wm.add_watch(handler.file_path, mask)   
notifier.loop() 
+0

필자는 pyinotify를 사용하지 않았지만 대신에 위에서 정의한 파일 찾기 방법을 사용하여 파일을 읽었습니다. 감사! – roymustang86

관련 문제