具有RotatingFileHandler的Python 3记录器超出maxBytes限制 [英] Python 3 logger with RotatingFileHandler excedes maxBytes limit

查看:60
本文介绍了具有RotatingFileHandler的Python 3记录器超出maxBytes限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码限制日志文件的大小(最小示例):

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)

但是,文件大小超过了1MB的限制,并继续记录日志.我看不到我在做什么错.有没有办法选择不同的参数来正确限制我的日志文件的大小?

However the file size excedes the limit of 1MB and keeps logging. 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)

我只是错过了backupCount = 1参数.但是,这将创建两个文件test.log和test.log.1(正确旋转文件似乎需要2个文件).这不是完美的解决方案,因为我只想拥有一个文件,但是对我来说很好用.

I simply missed out on the backupCount=1 parameter. This however creates two files test.log and test.log.1 (2 files seem to be needed for correct file rotations). Not the perfect solution since I would like to only have one file but it works well for me.

这篇关于具有RotatingFileHandler的Python 3记录器超出maxBytes限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆