2017-03-08 9 views
0

pyinotify과 그 스레드를 통해 로그 파일 쓰기 스트림을 유지하는 동안 문제가 발생합니다. CLOSE_WRITE 파일 이벤트에 대한 디렉터리를 모니터링하려면 pyinotify을 사용하고 있습니다. 내가 pyinotify를 초기화하기 전에 나는 내장 logging 모듈과 같이 사용하여 로그 스트림을 생성 : 내 __log 변수가 초기화 취득 후Python으로 Python으로 지속되는 로그 파일 스트림

import os, logging 
from logging import handlers 
from logging.config import dictConfig 


log_dir = './var/log' 
name = 'com.sadmicrowave.tesseract' 
LOG_SETTINGS = { 'version' : 1 
       ,'handlers': { 'core': { 
            # make the logger a rotating file handler so the file automatically gets archived and a new one gets created, preventing files from becoming too large they are unmaintainable. 
            'class'  : 'logging.handlers.RotatingFileHandler' 
            # by setting our logger to the DEBUG level (lowest level) we will include all other levels by default 
            ,'level'  : 'DEBUG' 
            # this references the 'core' handler located in the 'formatters' dict element below 
            ,'formatter' : 'core' 
            # the path and file name of the output log file 
            ,'filename'  : os.path.join(log_dir, "%s.log" % name) 
            ,'mode'   : 'a' 
            # the max size we want to log file to reach before it gets archived and a new file gets created 
            ,'maxBytes'  : 100000 
            # the max number of files we want to keep in archive 
            ,'backupCount' : 5 } 
          } 
          # create the formatters which are referenced in the handlers section above 
          ,'formatters': {'core': {'format': '%(levelname)s %(asctime)s %(module)s|%(funcName)s %(lineno)d: %(message)s' 
              } 
          } 
          ,'loggers' : {'root': { 
                 'level'  : 'DEBUG' # The most granular level of logging available in the log module 
                 ,'handlers' : ['core'] 
              } 
          } 
         } 

# use the built-in logger dict configuration tool to convert the dict to a logger config 
dictConfig(LOG_SETTINGS) 

# get the logger created in the config and named root in the 'loggers' section of the config 
__log = logging.getLogger('root') 

그래서,이 로그 기록을 허용, 즉시 작동합니다. 나는 옆에 pyinotify 인스턴스를 시작하려면 다음과 같은 클래스 정의를 사용 __log를 전달하고자 다음 pyinotify.AsyncNotifier에서 예상대로, 내 process_IN_CLOSE_WRITE 방법은 정확히 트리거됩니다 위의 구현에서

import asyncore, pyinotify 

class Notify (object): 
    def __init__ (self, log=None, verbose=True): 
     wm = pyinotify.WatchManager() 
     wm.add_watch('/path/to/folder/to/monitor/', pyinotify.IN_CLOSE_WRITE, proc_fun=processEvent(log, verbose)) 

     notifier = pyinotify.AsyncNotifier(wm, None) 
     asyncore.loop() 

class processEvent (pyinotify.ProcessEvent): 
    def __init__ (self, log=None, verbose=True): 
     log.info('logging some cool stuff') 

     self.__log    = log 
     self.__verbose   = verbose 

    def process_IN_CLOSE_WRITE (self, event): 
     print event 

을; 그러나 logging some cool stuff의 로그 라인은 로그 파일에 기록하지 않습니다.

파이널 팁 스레딩 프로세스를 통해 파일 스트림을 지속시키는 것과 관련이 있다고 생각합니다. 그러나이 문제를 해결하는 방법을 모르겠습니다.

아이디어가 있으십니까?

답변

0

해결할만한 해결책을 찾은 것 같습니다. 최선의 접근 방식인지 확실하지 않으므로 다른 아이디어가 게시되었는지 지금 OP를 열어 두겠습니다.

내가 pyinotify.AsyncNotifier 설정을 잘못 처리 한 것 같습니다.

class Notify (object): 
    def __init__ (self, log=None, verbose=True): 
     notifiers = [] 
     descriptors = [] 
     wm = pyinotify.WatchManager() 
     notifiers.append (pyinotify.AsyncNotifier(wm, processEvent(log, verbose))) 
     descriptors.append(wm.add_watch('/path/to/folder/to/monitor/', pyinotify.IN_CLOSE_WRITE, proc_fun=processEvent(log, verbose), auto_add=True) 

     asyncore.loop() 

이제 내 래퍼 클래스 processEvents는 청취자의 인스턴스 및 이벤트가 CLOSE_WRITE 이벤트에서 트리거 될 때 log 개체가 유지되는 트리거 적절하게 전달되는 경우에받을 수 있습니다 : 나는에 구현 변경 이벤트를 작성하십시오.

+0

유감스럽게도,'python-daemon'과'files_preserve'를 사용하여 demonization 요소를 추가하면 로그 스트림이 다시 사라지고 pyinotify 이벤트가 로그에 기록되지 않습니다 – sadmicrowave