且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使 Python 记录器将所有消息输出到标准输出以及日志文件

更新时间:2022-11-30 13:58:39

所有日志输出都由处理程序处理;只需添加一个 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)