我使用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
将被忽略。
现在,我想知道如何在line 3
中完成basicConfig
操作后将流更改为文件
发布于 2012-08-28 19:24:26
如果查看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')
https://stackoverflow.com/questions/12158048
复制相似问题