Easy logging in python

python
software engineering
snippets
Author

Salman Faris

Published

February 28, 2025

Don’t print. Log. The easiest way to log in python has to be to add this junk chunk at the top of your script.

import logging

logging.basicConfig(
    level=logging.INFO,  # Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
    format="%(asctime)s - %(levelname)s - %(message)s",  # Define the log format
    handlers=[
        logging.FileHandler("logfile.txt"),  # Log to a file
        logging.StreamHandler(),  # Log to the console
    ],
)

No package installs, everything straight out of the box. Then, you can just use

logging.info(...)

to log. The beautiful thing about this approach is that it logs to a specified file and logs to the console. Want even better coverage? Write a parallel cron job that pushes the updated log file to github in a scheduled period.

The days of training neural networks overnight and waking up to a dead computer with lost console logs are gone – yes, this was me in 2021… pathetic I know.