Explain Codes LogoExplain Codes Logo

How to write to a file, using the logging Python module?

python
logging
file-handling
exception-handling
Anton ShumikhinbyAnton Shumikhin·Feb 22, 2025
TLDR

Swiftly master Python's logging module to log messages to a file in the blink of an eye:

import logging # Looks like a cheat code to victory, right? logging.basicConfig(filename='victory_log.log', level=logging.INFO) # Voila, you just logged an info message. Congrats! logging.info('Another small step for a coder, a giant leap for coding kind.')

In only two lines, you've set up logging to direct output to a file called victory_log.log, catching messages at the INFO level and upwards.

Advanced configuration

Making the most out of handlers

To gain granular control over your log files, not only setting the severity level but also defining a custom log format, FileHandler comes to your rescue:

import logging # Get a shiny new logger, name it as you please logger = logging.getLogger('CodingNightmare') logger.setLevel(logging.DEBUG) # Capturing every tiny thing # Handlers, aka your loyal log minions file_handler = logging.FileHandler('coding_nightmare.log', 'a') # Append and NOT obliterate file_handler.setLevel(logging.ERROR) # We only care about errors here # Define the format of your nightmares log_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%H:%M:%S') file_handler.setFormatter(log_format) # Add your minion to the logger logger.addHandler(file_handler) # Now, unleash the logs! logger.error('Found a bug? Blame it on the intern.')

Organize your logging practices

Learn how to coordinate multiple loggers and handlers to power-charge your logging implementation.

Guardrails and adjustments

Import JSON, not problems:

Leveraging a configuration file for maintaining your loggers, handlers, and formatters can neatly separate logging infrastructure from your business logic. This practice comes handy for complex applications:

import logging.config logging.config.dictConfig('logging.json') logger = logging.getLogger('MyLifeInCode') logger.info('If life gives you problems, import solutions')

Traps & Treatments

Make sure the log file's path is accessible and implement exception handling to prevent crashes or lost logs:

try: file_handler = logging.FileHandler('/path/to/your/monologues.log') except (PermissionError, FileNotFoundError) as e: print(f'Error while logging: {e}')

Clean exit

Lastly, reminder to implement logging.shutdown() to ensure all logs have reached their destiny and handlers are properly closed. It's especially crucial if your program interacts with shared resources or operates in a multiprocessing environment.