Logging to Both File and Console in Python
Python logging provides robust functionality for message handling. By default, messages are typically written to a designated log file. However, you may also wish to duplicate these messages to the console, ensuring immediate visibility during program execution.
To achieve this, utilize the logging.StreamHandler class, which allows you to write logging output to sys.stdout, the standard output stream. Follow these steps:
Here's an example of how to configure a StreamHandler:
<code class="python">import logging import sys # Create a StreamHandler using sys.stdout handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) # Define a formatter and set it on the handler formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # Add the handler to the root logger root = logging.getLogger() root.addHandler(handler)</code>
By implementing these steps, you can conveniently output all logging messages to both the log file and the console, providing a comprehensive view of your application's logging activity.
The above is the detailed content of How to Log to Both File and Console in Python Using logging.StreamHandler?. For more information, please follow other related articles on the PHP Chinese website!