使 Python 记录器将所有消息输出到标准输出以及日志文件 [英] Making Python loggers output all messages to stdout in addition to log file

查看:41
本文介绍了使 Python 记录器将所有消息输出到标准输出以及日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用 logging 模块使 Python 日志记录自动输出到标准输出以及到它们应该去的日志文件?例如,我希望对 logger.warninglogger.criticallogger.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 记录器将所有消息输出到标准输出以及日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆