Home >Backend Development >Python Tutorial >How to Log to Stdout and Log File Simultaneously in Python?
Writing Logs to Stdout and Log File Simultaneously in Python
Controlling log output can be essential for debugging and capturing vital information in Python. The logging module provides extensive capabilities for logging messages to files. However, it can be beneficial to also display logs to the console (stdout) for immediate visibility.
Solution:
To ensure that all logging messages are output to stdout in addition to the designated log file, you can extend the functionality of the logging module by adding a logging.StreamHandler() to the root logger.
Implementation:
<code class="python">import logging import sys # Capture stdout stdout = sys.stdout # Create a root logger root = logging.getLogger() # Set the logging level (DEBUG in this case) root.setLevel(logging.DEBUG) # Define the StreamHandler handler = logging.StreamHandler(stdout) # Configure the message format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # Add the StreamHandler to the root logger root.addHandler(handler)</code>
With this modification, all messages logged using methods like logger.warning, logger.critical, and logger.error will be written to both the configured log file and displayed directly to stdout. This simplifies troubleshooting and ensures messages are easily accessible for inspection immediately.
The above is the detailed content of How to Log to Stdout and Log File Simultaneously in Python?. For more information, please follow other related articles on the PHP Chinese website!