简体   繁体   English

日志不要覆盖

[英]Logs Don't Overwrite

I'm using Python's logging.config module to configure and use a logging tool in my project.我正在使用 Python 的logging.config模块在我的项目中配置和使用日志记录工具。

I want my log files to overwrite each time (not append), so I set my YAML configuration file like this:我希望我的日志文件每次都被覆盖(而不是追加),所以我这样设置我的 YAML 配置文件:

# logging configuration file

version: 1
disable_existing_loggers: False

formatters:
    simple:
        format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

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

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

    error_file_handler:
        class: logging.handlers.RotatingFileHandler
        level: ERROR
        formatter: simple
        filename: .logs/errors.log
        maxBytes: 10485760 # 10MB
        backupCount: 20
        encoding: utf8
        mode: 'w'

loggers:
    my_module:
        level: ERROR
        handlers: [console]
        propagate: no

root:
    level: INFO
    handlers: [console, info_file_handler, error_file_handler]

This question mentions that using mode: w in the handler configuration should accomplish what I want, but the log files keep appending anyway. 这个问题提到在处理程序配置中使用mode: w应该可以完成我想要的,但是日志文件仍然会继续追加。 Here is my configuration code as well:这也是我的配置代码:

def logging_setup(cfg_path=definitions.LOG_CONFIG_PATH, def_lvl=logging.INFO):
    """Setup logging tool from YAML configuration file."""

    # create directory for log files if not already there
    try:
        os.makedirs(definitions.LOGS_PATH)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    # configure logging from yaml config file
    if os.path.exists(cfg_path):
        with open(cfg_path, 'rt') as f:
            config = yaml.load(f.read())

        logging.config.dictConfig(config)

    else:
        logging.basicConfig(level=def_lvl)

What am I doing incorrectly?我做错了什么?

Invoke doRollover() of the handler object will reset the file handler to overwrite old files before each run.调用处理程序对象的doRollover()将在每次运行之前重置文件处理程序以覆盖旧文件。

Python Logging Handlers - Rotating File Handler Python 日志处理程序 - 旋转文件处理程序

logging.handlers.RotatingFileHandler forces append mode by design. logging.handlers.RotatingFileHandler 通过设计强制 append 模式。 See logging/handlers.py :请参阅logging/handlers.py

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

Therefore, if you are only interested in the latest run, but have a lot of output that means a single log file is unmanageable, you need to delete the old log files yourself first:因此,如果您只对最新运行感兴趣,但有很多 output 意味着单个日志文件无法管理,您需要先自行删除旧日志文件:

def clean_up_log_files(logfile):
    """
    Cleans up the log file base_file_name and any rotated files.

    RotatingFileHandler is forced into append mode if the log size is specified.
    This means we can't rely on it to clean up our log files, and we have to do
    it for ourselves.

    Args:
        logfile     The log file name passed to RotatingFileHandler.
    """
    if os.path.exists(logfile):
        os.unlink(logfile)
    pattern = logfile + ".*"
    for file in glob(pattern):
        os.unlink(file)

I orginally used logging.handlers.RotatingFileHandler as the original handler class for my logger configuration.我最初使用logging.handlers.RotatingFileHandler作为我的记录器配置的原始处理程序类。 I did so because I am trying to minimize possible memory risks on a very small disk.我这样做是因为我试图将一个非常小的磁盘上可能存在的内存风险降到最低。 However: using logging.handlers.RotatingFileHandler instead of logging.FileHandler seems to disable the mode: 'w' option in the YAML configuration file.但是:使用logging.handlers.RotatingFileHandler而不是logging.FileHandler似乎禁用了mode: 'w' YAML 配置文件中的mode: 'w'选项。 The asker in the linked question seems to suggest he thinks this might be the issue, but the posted answers do not reflect that (thus my confusion). 链接问题中的提问者似乎暗示他认为这可能是问题所在,但发布的答案并未反映这一点(因此我很困惑)。

Using logging.FileHandler fixes my issue, allowing my log files to be overwritten each execution.使用logging.FileHandler修复了我的问题,允许在每次执行时覆盖我的日志文件。 I understand overwriting logs & rotating logs serve purposes that are in some amount of conflict with one another, but I thought having the safety that rotating logs offer with the desired convenience of overwritten logs would be best for my project.我理解覆盖日志和旋转日志服务的目的是相互之间存在某种程度的冲突,但我认为拥有旋转日志提供的安全性以及覆盖日志所需的便利对我的项目来说是最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM