本文介绍了为什么Python RotatingFileHandler'& quot; maxBytes& quot;不行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 logging 模块的RotatingFileHandler进行如下测试:

I'm trying to do a test run of the logging module's RotatingFileHandler as follows:

from logging import getLogger, Formatter
from logging.handlers import RotatingFileHandler

MAX_LOG_SIZE = 2000

_null = lambda *s: None
LOG_FORMAT = '%(process)d [%(name)s %(asctime)s] %(levelname)s: %(message)s'

class Logger(object):
    __slots__ = '_Logger__logger'

    def __init__(self, name='main'):
        self.__logger = getLogger(name)
        if not self.__logger.handlers:
            self.add_handler(name)

    def add_handler(self, name):

        file_name = 'log.log'
        handler = RotatingFileHandler(file_name, 'a+', MAX_LOG_SIZE)
        handler.setFormatter(Formatter(LOG_FORMAT))
        self.__logger.addHandler(handler)
        self.__logger._file_name = file_name

    def ERROR(self, msg, *args):
        self.__logger.error(msg, *args, **{})

if __name__ == '__main__':
    logger = Logger()
    for i in range(1000):
        logger.ERROR('logger.content')

但是,在MAX_LOG_SIZE = 2000的情况下,log.log文件的结果包含的数据量大于2000字节

However, with MAX_LOG_SIZE = 2000, the resulting of log.log file contains too much data large than 2000 bytes

如何限制日志文件的最大大小?

How can I limit max size of the logfile?

推荐答案

您需要阅读文档更加小心:您缺少kwargs maxBytes backupCount .

You need to read the documentation more carefully: you are missing the kwargs maxBytes and backupCount.

替换此

handler = RotatingFileHandler(file_name, 'a+', MAX_LOG_SIZE)

为此

handler = RotatingFileHandler(file_name, 'a+', maxBytes=MAX_LOG_SIZE, backupCount=5)

请注意,您应该设置一个满足您需要的 backupCount 值,我只是使用了一个随机值.

Notice you shall set a backupCount value that fits your needs, I just used a random one.

您的代码为何不滚动文件的进一步说明是因为值 backupCount 为0.请参见以下内容:

A further explanation of why your piece of code does not roll the file is because the value backupCount is 0. See the following:

这篇关于为什么Python RotatingFileHandler'& quot; maxBytes& quot;不行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:12