Home >Backend Development >Python Tutorial >How to Output Python Logger Messages to Standard Output (Stdout)?
Redirect Python Logger Output to Stdout
In Python's logging module, messages are typically written to specific log files based on their logging level. However, you may need all log messages to be outputted not only to the log file but also to standard output (stdout) for troubleshooting or monitoring purposes.
To achieve this, you can utilize the logging.StreamHandler() class, which allows you to redirect logging output to stdout. The process involves adding the StreamHandler to the root logger, which controls all other loggers.
Code Example:
<code class="python">import logging import sys # Retrieve the root logger root = logging.getLogger() # Set the root logger's logging level (optional, if needed) root.setLevel(logging.DEBUG) # Create a StreamHandler that redirects logging output to stdout handler = logging.StreamHandler(sys.stdout) # Set the logging level for the handler (optional, if needed) handler.setLevel(logging.DEBUG) # Define a formatter for the log messages formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # Set the formatter for the handler handler.setFormatter(formatter) # Add the StreamHandler to the root logger root.addHandler(handler)</code>
With this code in place, all logging messages generated by the logger.warning, logger.critical, and logger.error methods will be written to both the log file and stdout, allowing for convenient access to crucial error and warning messages during development or monitoring operations.
The above is the detailed content of How to Output Python Logger Messages to Standard Output (Stdout)?. For more information, please follow other related articles on the PHP Chinese website!