Home  >  Article  >  Backend Development  >  How to Output Logging Messages to Both Log File and Stdout in Python?

How to Output Logging Messages to Both Log File and Stdout in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-18 19:02:29648browse

How to Output Logging Messages to Both Log File and Stdout in Python?

Preserving Message Integrity with Python Logging: Outputting to Both Log File and stdout

When utilizing Python's logging module, it's often desirable to simultaneously output log messages to both a log file and stdout. This ensures comprehensive logging while allowing real-time visibility for critical or warning messages.

To achieve this, leverage the power of handlers, which control the destination of logging messages. By adding a logging.StreamHandler() to the root logger, you can effortlessly direct output to stdout.

Here's an illustrative example:

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

# Configure the root logger with appropriate level
root = logging.getLogger()
root.setLevel(logging.DEBUG)

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

# Add a formatter to enhance readability
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

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

By incorporating this code into your logging configuration, you can ensure that all log messages (error, warning, critical) are not only written to your specified log file but also conveniently displayed on stdout. This eliminates the need for redundant print statements and provides a comprehensive view of your application's logging activities.

The above is the detailed content of How to Output Logging Messages to Both Log File and Stdout in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn