How do I configure logging to file and console?

To configure logging to both a file and the console in Python, you can use the built-in `logging` module. Below is an example of how to set up logging to output messages to both a log file and the console simultaneously.

import logging # Create a logger logger = logging.getLogger('my_logger') logger.setLevel(logging.DEBUG) # Create file handler file_handler = logging.FileHandler('app.log') file_handler.setLevel(logging.INFO) # Create console handler console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) # Create a formatter and set it for both handlers formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) console_handler.setFormatter(formatter) # Add handlers to the logger logger.addHandler(file_handler) logger.addHandler(console_handler) # Example logging messages logger.debug('This is a debug message') logger.info('This is an info message') logger.warning('This is a warning message') logger.error('This is an error message') logger.critical('This is a critical message')

python logging file logging console logging logger configuration