首页  >  文章  >  后端开发  >  如何使用 Python 日志模块记录到文件和标准输出?

如何使用 Python 日志模块记录到文件和标准输出?

Barbara Streisand
Barbara Streisand原创
2024-10-18 18:58:29272浏览

How to Log to Both File and Stdout using the Python Logging Module?

使用日志模块在 Python 中记录到文件和标准输出

使用 Python 日志模块时,希望输出日志消息不仅可以发送到指定的日志文件,还可以发送到标准输出以立即可见。为了实现这一点,日志记录模块提供了一个简单的解决方案。

日志记录配置依赖于处理程序来直接输出。通过将logging.StreamHandler()实例添加到根记录器,除了其预期目的地之外,还可以将消息发送到stdout。

为stdout输出配置流处理程序的示例:

<code class="python">import logging
import sys

# Get the root logger
root = logging.getLogger()

# Set the root logger level to DEBUG
root.setLevel(logging.DEBUG)

# Create a stream handler and set its level to DEBUG
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)

# Create a formatter to format the log messages
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# Add the handler to the root logger
root.addHandler(handler)</code>

通过实现此配置,无需使用记录器方法和标准输出打印语句来复制日志消息。 mylogger.ritic("something failed") 等记录器将输出到指定的日志文件和标准输出,提供即时可见性,同时保持正确的日志记录实践。

以上是如何使用 Python 日志模块记录到文件和标准输出?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn