How to log to file and console simultaneously in Python

Better Stack Team
Updated on August 25, 2023

To log to both a file and the console simultaneously in Python, you need to set up two handlers for the logger: one for writing logs to a file and another for printing logs to the console. The logging module in Python makes it straightforward to achieve this. Here's an example of how to log to both file and console:

import logging

# Create a logger
logger = logging.getLogger('my_logger')

# Create a formatter to define the log format
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

# Create a file handler to write logs to a file
file_handler = logging.FileHandler('app.log')

# Create a stream handler to print logs to the console
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)  # You can set the desired log level for console output

# Add the handlers to the logger

# Now you can log messages with different levels
logger.debug('This is a debug message')'This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')

In this example, we create two handlers, file_handler and console_handler, with different log levels. The file_handler is set to log all messages with level DEBUG and above to the file "app.log." The console_handler is set to log messages with level INFO and above to the console. You can adjust the log levels and formats according to your preferences.

With this setup, logs of the specified severity levels will be written to both the file "app.log" and the console simultaneously.

To learn more about logging in Python, visit Better Stack Community.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →