import logging
import auxiliary_module
# create logger with 'spam_application'
log = logging.getLogger('spam_application')
log.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
ch.setFormatter(formatter)
log.addHandler(ch)
log.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
log.info('created an instance of auxiliary_module.Auxiliary')
log.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
log.info('finished auxiliary_module.Auxiliary.do_something')
log.info('calling auxiliary_module.some_function()')
auxiliary_module.some_function()
log.info('done with auxiliary_module.some_function()')
# remember to close the handlers
for handler in log.handlers:
handler.close()
log.removeFilter(handler)
7 回答
所有日志记录输出都由处理程序处理;只需将logging.StreamHandler()添加到根 Logger .
以下是配置流处理程序(使用
stdout
而不是默认stderr
)并将其添加到根 Logger 的示例:最简单的方法:
可以使用多个处理程序 .
请参阅:https://docs.python.org/2/howto/logging-cookbook.html
您可以为file和stdout创建两个处理程序,然后使用
handlers
参数为basicConfig创建一个 Logger . 如果两个处理程序具有相同的log_level和format输出,那么它可能很有用:记录到文件和stderr的最简单方法:
这是基于dictConfig configuration function的解决方案 . 它不是将每条日志消息发送到stdout,而是将日志级别为ERROR且更高的消息发送到stderr,将其他所有内容发送到stdout . 如果系统的其他部分正在侦听stderr / stdout,这可能很有用 .
看一下loguru模块 .