mode ='w'仅适用于logging.FileHandler,不适用于logging.handlers.RotatingFileHandler

时间:2019-06-26 12:10:07

标签: python-3.x logging

我正在尝试使用以下日志记录配置来创建日志。 但是在处理程序'info_file_handler'中,模式:'w'不会使用class: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

1 个答案:

答案 0 :(得分:0)

我有同样的问题。如何在每次记录时旋转文件从指定的文件大小旋转开始。 从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'

IMO。似乎除了'a'以外的其他模式都没有用,因此可以删除'mode'。(?)