简体   繁体   English

如何在根记录器中使用RotatingFileHandler

[英]How to use RotatingFileHandler with the root logger

I configure the root logger: 我配置了根记录器:

logging.basicConfig(filename='logfile.log', level=logging.DEBUG)

Then I put log messages in my code like this: 然后,将日志消息放入我的代码中,如下所示:

logging.debug("This is a log message")

Question : How do I add a RotatingFileHandler such that my logs will be rotated? 问题 :如何添加RotatingFileHandler以便日志被轮换?

Note: I do not want a logger instance which I then have to pass around everywhere. 注意:我想要一个记录器实例,然后我必须到处传递它。

You can do this by using the handlers kwarg of basicConfig. 您可以通过使用basicConfig的handlers kwarg来实现。 Be aware that this needs to be an iterable and you can not use the filename argument together with it. 请注意,这需要是可迭代的,并且不能与filename参数一起使用。

import logging
import logging.handlers

rot_handler = logging.handlers.RotatingFileHandler('filename.txt')
logging.basicConfig(level=logging.DEBUG, handlers=[rot_handler])

Link to relevant part of documentation: https://docs.python.org/3/library/logging.html#logging.basicConfig 链接到文档的相关部分: https : //docs.python.org/3/library/logging.html#logging.basicConfig

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

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