使Python记录器将除日志文件外的所有消息输出到stdout [英] Making Python loggers output all messages to stdout in addition to log file
问题描述
是否有一种使用logging
模块进行Python日志记录的方法,可以自动将东西输出到stdout 到应该存放它们的日志文件中?例如,我希望所有对logger.warning
,logger.critical
,logger.error
的调用都移至其预期的位置,但除此之外,总是将其复制到stdout
.这是为了避免重复消息,例如:
Is there a way to make Python logging using the logging
module automatically output things to stdout in addition to the log file where they are supposed to go? For example, I'd like all calls to logger.warning
, logger.critical
, logger.error
to go to their intended places but in addition always be copied to stdout
. This is to avoid duplicating messages like:
mylogger.critical("something failed")
print "something failed"
推荐答案
所有日志记录输出均由处理程序处理;只需在根记录器中添加 logging.StreamHandler()
.
All logging output is handled by the handlers; just add a logging.StreamHandler()
to the root logger.
下面是配置流处理程序(使用stdout
而不是默认的stderr
)并将其添加到根记录器的示例:
Here's an example configuring a stream handler (using stdout
instead of the default stderr
) and adding it to the root logger:
import logging
import sys
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)
这篇关于使Python记录器将除日志文件外的所有消息输出到stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!