Home  >  Article  >  Backend Development  >  How to Log to Both File and Stdout using the Python Logging Module?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-18 18:58:29366browse

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

Logging to Both File and Stdout in Python with the Logging Module

When utilizing the Python logging module, it's desirable to have log messages output not only to the specified log file but also to stdout for immediate visibility. To achieve this, the logging module provides a straightforward solution.

The logging configuration relies on handlers to direct output. By adding a logging.StreamHandler() instance to the root logger, it's possible to send messages to stdout in addition to their intended destinations.

An example of configuring a stream handler for stdout output:

<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>

By implementing this configuration, it becomes unnecessary to duplicate log messages using both logger methods and stdout print statements. Loggers such as mylogger.critical("something failed") will output to both the designated log file and stdout, providing immediate visibility while maintaining proper logging practices.

The above is the detailed content of How to Log to Both File and Stdout using the Python Logging Module?. 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