[英]Why does Python RotatingFileHandler's “maxBytes ” not work
I'm trying to do a test run of the logging
module's RotatingFileHandler as follows: 我正在尝试对logging
模块的RotatingFileHandler进行如下测试:
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')
However, with MAX_LOG_SIZE = 2000, the resulting of log.log file contains too much data large than 2000 bytes 但是,在MAX_LOG_SIZE = 2000的情况下,log.log文件的结果包含的数据量大于2000字节
How can I limit max size of the logfile? 如何限制日志文件的最大大小?
You need to read the documentation more carefully: you are missing the kwargs maxBytes
and backupCount
. 您需要更仔细地阅读文档 :您缺少kwargs maxBytes
和backupCount
。
Replace this 取代这个
handler = RotatingFileHandler(file_name, 'a+', MAX_LOG_SIZE)
for this 为了这
handler = RotatingFileHandler(file_name, 'a+', maxBytes=MAX_LOG_SIZE, backupCount=5)
Notice you shall set a backupCount
value that fits your needs, I just used a random one. 注意,您应该设置一个适合您需要的backupCount
值,我只是使用了一个随机数。
A further explanation of why your piece of code does not roll the file is because the value backupCount
is 0. See the following: 为什么您的代码段不滚动文件的进一步说明是因为值backupCount
为0。请参见以下内容:
You can use the maxBytes and backupCount values to allow the file to rollover at a predetermined size. 您可以使用maxBytes和backupCount值来允许文件以预定大小滚动。 When the size is about to be exceeded, the file is closed and a new file is silently opened for output. 当将要超过该大小时,将关闭该文件,并以静默方式打开一个新文件以进行输出。 Rollover occurs whenever the current log file is nearly maxBytes in length; 每当当前日志文件的长度接近maxBytes时,就会发生翻转。 but if either of maxBytes or backupCount is zero, rollover never occurs, so you generally want to set backupCount to at least 1, and have a non-zero maxBytes. 但是如果maxBytes或backupCount中的任何一个为零,则永远不会发生过渡,因此通常需要将backupCount设置为至少1,并且maxBytes为非零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.