将RotatingFileHandler添加到Watchdog日志记录中

时间:2017-09-08 09:00:18

标签: python python-watchdog

我正在尝试将RotatingFileHandler添加到我的Watchdog中,这样我就可以保持日志文件的增长。为了便于说明,我将使用Watchdog Quickstart Example

我发现thread解释了如何实现Pythons'记录RotatingFileHandler,但是当我尝试组合两个脚本时,我遇到了困难:

if __name__ == "__main__":
    logging.basicConfig(filename='test.log',  # added filename for convencience
                        level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')

    # edited Quickstart example with RotatingFileHandler here
    logger = logging.getLogger('test')
    handler = RotatingFileHandler("test.log", maxBytes=2000, backupCount=2)
    logger.addHandler(handler)

    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

代码不会产生任何错误,但会像往常一样保持日志记录。我怀疑RotatingFileHandler只传递给常规记录器,而不是传递给LoggingEventHandler,但我不知道如何将它传递给正确的处理程序。

非常感谢任何提示,

此致

2 个答案:

答案 0 :(得分:1)

查看看门狗关于LoggingEventHandlerhttp://pythonhosted.org/watchdog/_modules/watchdog/events.html#LoggingEventHandler

的源代码

如您所见,LoggingEventHandler只需使用logging进行记录。您需要做的是实施自定义LoggingEventHandler

例如:

class CustomLoggingEventHandler(LoggingEventHandler):
    """Logs all the events captured."""

    def __init__(self, logger):
        self.logger = logger

    def on_moved(self, event):
        super().on_moved(event)

        what = 'directory' if event.is_directory else 'file'
        self.logger.info("Moved %s: from %s to %s", what, event.src_path,
                     event.dest_path)

    def on_created(self, event):
        super().on_created(event)

        what = 'directory' if event.is_directory else 'file'
        self.logger.info("Created %s: %s", what, event.src_path)

    def on_deleted(self, event):
        super().on_deleted(event)

        what = 'directory' if event.is_directory else 'file'
        self.logger.info("Deleted %s: %s", what, event.src_path)

    def on_modified(self, event):
        super().on_modified(event)

        what = 'directory' if event.is_directory else 'file'
        self.logger.info("Modified %s: %s", what, event.src_path)

然后使用您的自定义LoggingEventHandler

event_handler = CustomLoggingEventHandler(logger)
observer = Observer()
observer.schedule(event_handler, path, recursive=True)

答案 1 :(得分:0)

调用logging.basicConfig()时,您可以将RotatingFileHandler作为参数传递:

logging.basicConfig(
        handlers=[RotatingFileHandler('./my_log.log', maxBytes=100000, backupCount=10)],
        level=logging.DEBUG,
        format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
        datefmt='%Y-%m-%dT%H:%M:%S')

将其应用于Quickstart example

import sys
import time
import logging
from logging.handlers import RotatingFileHandler
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        handlers=[RotatingFileHandler('./my_log.log', maxBytes=100000, backupCount=10)])
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

非常感谢this answer的提示。