首页 > 解决方案 > mode = 'w' 仅适用于 logging.FileHandler 但不适用于 logging.handlers.RotatingFileHandler

问题描述

我正在尝试使用以下日志记录配置创建日志。但是在处理程序'info_file_handler'中,模式:'w'不会用类覆盖文件:logging.handlers.RotatingFileHandler。我应该用 logging.FileHandler 替换类,输出日志文件被覆盖。logging.handlers.RotatingFileHandler 需要在这里添加一些额外的代码吗?

# https://gist.github.com/kingspp/9451566a5555fb022215ca2b7b802f19
version: 1
disable_existing_loggers: true
formatters:
    standard:
        # format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        format: "%(levelname)s: %(message)s"
    error:
        format: "%(levelname)s <PID %(process)d:%(processName)s> %(name)s.%(funcName)s(): %(message)s"

handlers:
    console:
        class: logging.StreamHandler
        level: DEBUG
        formatter: standard
        stream: ext://sys.stdout

    info_file_handler:
        class: logging.handlers.RotatingFileHandler
        level: INFO
        formatter: standard
        filename: info.log
        mode: 'w'
        maxBytes: 10485760 # 10MB
        backupCount: 20
        encoding: utf8

root:
    level: NOTSET
    handlers: [console]
    propogate: no

loggers:
    my_module:
        level: INFO
        handlers: [info_file_handler]
        propogate: no

标签: python-3.xlogging

解决方案


我也有同样的问题。如何在每次记录时轮换文件从指定的文件大小轮换开始。从 logging.handlers :

        If maxBytes is zero, rollover never occurs.
        """
        # If rotation/rollover is wanted, it doesn't make sense to use another
        # mode. If for example 'w' were specified, then if there were multiple
        # runs of the calling application, the logs from previous runs would be
        # lost if the 'w' is respected, because the log file would be truncated
        # on each run.
        if maxBytes > 0:
            mode = 'a'

国际海事组织。似乎除“a”之外的另一种模式没用,因此可以删除“模式”。(?)


推荐阅读