更改已设置的日志记录的"basicConfig" [英] Changing logging's 'basicConfig' which is already set
问题描述
我在python中使用日志记录模块为:
I am using the logging module in python as:
import logging, sys
logger= logging.getLogger(__file__)
logging.basicConfig(stream = sys.stderr, level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s')
logger.debug("Hello World")
现在,在line 3
上设置基本配置后,我想要一个命令行参数,该参数可以将输出流从sys.stderr更改为文件.
Now, after I have set the basic configuration on line 3
, I want to have a command line argument that can change the output stream from sys.stderr to a file.
我已经阅读了文档,并说如果同时出现filename
和stream
,则会忽略stream
.
I have read the doc and it says that if both filename
and stream
are present at the same time, the stream
is ignored.
现在,我想知道在完成line 3
中的basicConfig
事情后如何将流更改为文件吗?
Now, I wanna know how do change the stream to a file after I have already done the basicConfig
thing in line 3
?
推荐答案
如果在logging/__init__.py
的Python源代码中查找,您会看到basicConfig()
通过调用addHandler()
在根记录器对象上设置处理程序. .如果您想从头开始,则可以删除所有现有的处理程序,然后再次调用basicConfig()
.
If you look in the Python sources for logging/__init__.py
, you'll see that basicConfig()
sets the handlers on the root logger object by calling addHandler()
. If you want to start from scratch, you could remove all existing handlers and then call basicConfig()
again.
# Example to remove all root logger handlers and reconfigure. (UNTESTED)
import logging
# Remove all handlers associated with the root logger object.
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
# Reconfigure logging again, this time with a file.
logging.basicConfig(filename = 'myfile.log', level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s')
这篇关于更改已设置的日志记录的"basicConfig"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!