0

我正在尝试将 RotatingFileHandler 添加到我的看门狗中,让我能够控制日志文件的增长。出于说明目的,我将使用Watchdog 快速入门示例

我找到了一个解释如何实现 Python 的日志记录 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,但我不知道如何将它传递给正确的处理程序。

非常感谢任何提示,

问候

4

2 回答 2

1

检查看门狗的源代码LoggingEventHandler: http: //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)
于 2017-09-08T09:18:49.727 回答
0

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

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

将其应用于快速入门示例

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

非常感谢这个答案的提示。

于 2020-07-11T00:24:22.120 回答