如何使用Python的RotatingFileHandler [英] How to use Python's RotatingFileHandler
问题描述
我正在尝试对logging
模块的RotatingFileHandler
进行如下测试:
I'm trying to do a test run of the logging
module's RotatingFileHandler
as follows:
import logging
from logging.handlers import RotatingFileHandler
# logging.basicConfig(filename="example.log", level=logging.DEBUG)
logger = logging.getLogger('my_logger')
handler = RotatingFileHandler("my_log.log", maxBytes=2000, backupCount=10)
logger.addHandler(handler)
for _ in range(10000):
logger.debug("Hello, world!")
但是,在注释掉logging.basicConfig
行的情况下,生成的my_log.log
文件不包含任何数据:
However, with logging.basicConfig
line commented out, the resulting my_log.log
file contains no data:
如果我在logging.basicConfig(filename="example.log", level=logging.DEBUG)
行中注释,则会得到带有编号后缀的预期my_log.log
文件.但是,还有example.log
这是一个(相对)较大的文件:
If I comment in the line with logging.basicConfig(filename="example.log", level=logging.DEBUG)
, I get the expected my_log.log
files with numbered suffixes. However, there is also the example.log
which is a (relatively) large file:
如何设置日志记录,使其仅生成my_log.log
文件,而不生成较大的example.log
文件?
How can I set up the logging so that it only generates the my_log.log
files, and not the large example.log
file?
推荐答案
Python提供了5个开箱即用的日志记录级别(按严重性从高到低的顺序):DEBUG
,INFO
,WARNING
,ERROR
和CRITICAL
. WARNING
默认为 .文档说,
Python provides 5 logging levels out of the box (in increasing order of severity): DEBUG
, INFO
, WARNING
, ERROR
and CRITICAL
. The default one is WARNING
. The docs says, that
严重程度低于 lvl 的日志消息将被忽略.
Logging messages which are less severe than lvl will be ignored.
因此,如果将.debug
用于默认设置,则日志中将不会看到任何内容.
So if you use .debug
with the default settings, you won't see anything in your logs.
最简单的解决方法是使用logger.warning
函数而不是logger.debug
:
The easiest fix would be to use logger.warning
function rather that logger.debug
:
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger('my_logger')
handler = RotatingFileHandler('my_log.log', maxBytes=2000, backupCount=10)
logger.addHandler(handler)
for _ in range(10000):
logger.warning('Hello, world!')
如果您想更改记录器级别,则可以使用 .setLevel
方法:
And if you want to change logger level you can use .setLevel
method:
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
handler = RotatingFileHandler('my_log.log', maxBytes=2000, backupCount=10)
logger.addHandler(handler)
for _ in range(10000):
logger.debug('Hello, world!')
这篇关于如何使用Python的RotatingFileHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!