簡體   English   中英

帶有PyInotify的Python持久日志文件流

[英]Python Persist Log File Stream with PyInotify

我遇到一個問題,即通過pyinotify及其線程持久保存日志文件寫入流。 我正在使用pyinotify監視目錄中的CLOSE_WRITE文件事件。 在初始化pyinotify之前,我使用內置的logging模塊創建日志流,如下所示:

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')

因此,在我的__log變量初始化之后,它可以立即工作,允許進行日志寫入。 我想接下來啟動pyinotify實例,並想使用以下類定義傳遞__log

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

在上面的實現中,我的process_IN_CLOSE_WRITE方法完全從pyinotify.AsyncNotifier得到了預期的pyinotify.AsyncNotifier 但是,用於logging some cool stuff的日志行永遠不會寫入日志文件。

我覺得這與通過pyinotify線程過程持久化文件流有關; 但是,我不確定該如何解決。

有任何想法嗎?

我可能已經找到了一種可行的解決方案。 不確定這是否是最好的方法,因此我暫時將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對象將得到適當維護和傳遞,並且可以接收寫入事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM