我在python中使用日志记录模块:
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更改为文件。
我已阅读该文档,并说如果filename
和stream
同时存在,stream
将被忽略。
现在,我想知道在basicConfig
完成line 3
之后,如何将流更改为文件?
答案 0 :(得分:49)
如果您查看logging/__init__.py
的Python源代码,您会看到basicConfig()
通过调用addHandler()
来设置根记录器对象上的处理程序。如果您想从头开始,可以删除所有现有处理程序,然后再次调用basicConfig()
。
# 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')