How to Setup Logging in Python

Python Logging

What is Python logging

Python logging is a module that comes packaged in the standard library. It's a flexible framework that allows you to set logging levels to customize the amount of diagnostic information your application emits.

Not only does it look professional, but it's also incredibly simple to implement in any python application.

Python Logging Configuration

Below is sample code for getting started with the Python Logger.

 Python Logger Example:
import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="{asctime} {levelname:<8} {message}",
    style='{',
    filename='%slog' % __file__[:-2],
    filemode='a'
)

Let's break the configuration down.

Python Logging Levels

The python logger will only display log messages of the log level it is set to and higher. Have a look at the table below.

Level Numeric Value
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10

By default, the Python logger will show logging messages of "WARNING" and higher. However, in our code we have set the logging level to DEBUG, so we will get all logging messages.

Below is example code on how to use logging messages.

logging.critical('This is a critical level msg!')
logging.error('This is a error level msg!')
logging.warning('This is a warning level msg!')
logging.info('This is a info level msg!')
logging.debug('This is a debug level msg!')

Python Logging formats

The format I use in most of my applications looks like below:

 format="{asctime} {levelname:<8} {message}"

This provides a timestamp, the logging level, and a message. Here's an example of the output

2020-10-18 16:56:43,013 CRITICAL There was an error with user

Logging to a File or to the console

The below options will log to a file in "Append" mode. If you wish to overwrite old log files, change the filemode to W. If you wish to log directly to the console do not use the filename or filemode options.

    filename='%slog' % __file__[:-2],
    filemode='a'

I hope this article was helpful. There's plenty more content and explanation in the video if you need it. Good luck and have fun!