如何使用 Python 的 RotatingFileHandler

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40088496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:09:33  来源:igfitidea点击:

How to use Python's RotatingFileHandler

pythonlogging

提问by Kurt Peek

I'm trying to do a test run of the loggingmodule's RotatingFileHandleras follows:

我正在尝试对logging模块RotatingFileHandler进行如下测试:

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!")

However, with logging.basicConfigline commented out, the resulting my_log.logfile contains no data:

但是,logging.basicConfig注释掉行后,生成的my_log.log文件不包含任何数据:

enter image description here

在此处输入图片说明

If I comment in the line with logging.basicConfig(filename="example.log", level=logging.DEBUG), I get the expected my_log.logfiles with numbered suffixes. However, there is also the example.logwhich is a (relatively) large file:

如果我在行中添加注释logging.basicConfig(filename="example.log", level=logging.DEBUG),我会得到my_log.log带有编号后缀的预期文件。但是,还有example.log一个(相对)大的文件:

enter image description here

在此处输入图片说明

How can I set up the logging so that it only generates the my_log.logfiles, and not the large example.logfile?

如何设置日志记录,使其只生成my_log.log文件,而不生成大example.log文件?

采纳答案by skovorodkin

Python provides 5 logging levels out of the box (in increasing order of severity): DEBUG, INFO, WARNING, ERRORand CRITICAL. The default one is WARNING. The docs says, that

Python提供5个日志级别开箱(严重程度的增加顺序): ,DEBUG,,和。默认. 文档说,那INFOWARNINGERRORCRITICALWARNING

Logging messages which are less severe than lvlwill be ignored.

lvl严重的日志消息将被忽略。

So if you use .debugwith the default settings, you won't see anything in your logs.

因此,如果您使用.debug默认设置,您将不会在日志中看到任何内容。

The easiest fix would be to use logger.warningfunction rather that logger.debug:

最简单的解决方法是使用logger.warning函数而不是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!')

And if you want to change logger level you can use .setLevelmethod:

如果你想改变记录器级别,你可以使用.setLevel方法:

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!')

回答by Thomas Burke

Going off of Kurt Peek's answer you can also put the rotating file handler in the logging.basicConfig directly

从 Kurt Peek 的回答开始,您还可以直接将旋转文件处理程序放在 logging.basicConfig 中

import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(
        handlers=[RotatingFileHandler('./my_log.log', maxBytes=100000, backupCount=10)],
        level=logging.DEBUG,
        format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
        datefmt='%Y-%m-%dT%H:%M:%S')

回答by grepit

All previous answers are correct, here another way of doing the same thing except we use logging config file instead.

所有以前的答案都是正确的,这里是另一种做同样事情的方式,除了我们使用日志配置文件。

logging_config.ini

日志配置文件

Here is the config file :

这是配置文件:

[loggers]
keys=root

[handlers]
keys=logfile

[formatters]
keys=logfileformatter

[logger_root]
level=DEBUG
handlers=logfile

[formatter_logfileformatter]
format=%(asctime)s %(name)-12s: %(levelname)s %(message)s

[handler_logfile]
class=handlers.RotatingFileHandler
level=DEBUG
args=('testing.log','a',10,100)
formatter=logfileformatter

myScrypt.py

myScrypt.py

here is simple logging script that uses the above config file

这是使用上述配置文件的简单日志记录脚本

import logging
from logging.config import fileConfig

fileConfig('logging_config.ini')
logger = logging.getLogger()
logger.debug('the best scripting language is python in the world')

RESULT

结果

here is the result, notice maxBytes is set to 10 but in real life, that's clearly too small. (args=('testing.log','a',10,100)

这是结果,注意 maxBytes 设置为 10 但在现实生活中,这显然太小了。(args=('testing.log','a',10,100)

enter image description here

在此处输入图片说明

回答by Kurt Peek

I found that to obtain the desired behavior one has to use the same name in the basicConfigand RotatingFileHandlerinitializations:

我发现要获得所需的行为,必须在basicConfigRotatingFileHandler初始化中使用相同的名称:

import logging
from logging.handlers import RotatingFileHandler

logging.basicConfig(filename="my_log.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!")

Here, I have chose the same name my_log.log. This results in only the 'size-limited' logs being created:

在这里,我选择了相同的名称my_log.log。这导致仅创建“大小受限”日志:

enter image description here

在此处输入图片说明