我使用以下代码来限制日志文件的大小(最小示例):
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)
然而,文件大小超出了1MB的限制并保持记录。我不知道自己做错了什么。有没有办法选择不同的参数来正确限制我的日志文件的大小?
答案 0 :(得分:0)
好吧,好像我找到了解决我问题的解决方法:
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)
我错过了backupCount = 1参数。然而,这会创建两个文件test.log和test.log.1(正确的文件轮换似乎需要2个文件)。不是完美的解决方案,因为我只想拥有一个文件,但它对我来说效果很好。