简体   繁体   English

具有RotatingFileHandler的Python 3记录器超过maxBytes限制

[英]Python 3 logger with RotatingFileHandler excedes maxBytes limit

I am using the following code to limit the size of a logfile (minimal example): 我正在使用以下代码来限制日志文件的大小(最小示例):

import logging
from logging.handlers import RotatingFileHandler

# Set up logfile and message logging.
logger = logging.getLogger("Logger")
logger.setLevel(logging.ERROR)
# Create the rotating file handler. Limit the size to 1000000Bytes ~ 1MB .
handler = RotatingFileHandler("test.log", mode='a', maxBytes=1000000, encoding=None, delay=0)
handler.setLevel(logging.ERROR)
# Create a formatter.
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Add handler and formatter.
handler.setFormatter(formatter)
logger.addHandler(handler)

for l in range(1000):
    logger.error("test" * 1000)

However the file size excedes the limit of 1MB and keeps logging. 但是,文件大小超出了1MB的限制,并继续记录日志。 I don't see what I am doing wrong. 我看不到我在做什么错。 Is there a way to choose different parameters to correctly limit the size of my logfile? 有没有办法选择不同的参数来正确限制日志文件的大小?

Ok it seems I found a workaround that solves my problem: 好的,看来我找到了一种解决方法来解决我的问题:

import logging
from logging.handlers import RotatingFileHandler

# Set up logfile and message logging.
logger = logging.getLogger("Logger")
logger.setLevel(logging.ERROR)
# Create the rotating file handler. Limit the size to 1000000Bytes ~ 1MB .
handler = RotatingFileHandler("test.log", mode='a', maxBytes=1000000, backupCount=1, encoding='utf-8', delay=0)
handler.setLevel(logging.ERROR)
# Create a formatter.
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Add handler and formatter.
handler.setFormatter(formatter)
logger.addHandler(handler)

for l in range(1000):
    logger.error("test" * 1000)

I simply missed out on the backupCount=1 parameter. 我只是错过了backupCount = 1参数。 This however creates two files test.log and test.log.1 (2 files seem to be needed for correct file rotations). 但是,这将创建两个文件test.log和test.log.1(正确旋转文件似乎需要2个文件)。 Not the perfect solution since I would like to only have one file but it works well for me. 这不是完美的解决方案,因为我只想拥有一个文件,但对我来说很好用。

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

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