Super simple Django error logging configuration, good for Heroku

June 29, 2016

Here's a really simple logging configuration for Django to output anything of the level 'Error' and up to the console.

Heroku's logging functionality allows you to monitor application messaging in real time in your production environment. Just put the code below in the bottom of your settings file.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'),
        },
    },
}

Then run the following Heroku command to display application messages in real time:

heroku logs --source app --tail


What's going on here?

We'll break this down into each individual section:

'version': 1

Identifies the format of the logging dictionary. Currently there is only 1 version available, but there could be more in the future.

'disable_existing_loggers': False,

This indicates that we shouldn't disable the default logging configuration. The default is 'True', but it's not recommended to do this, as the default logs can be useful. Instead we will keep the default logs and redefine certain elements of them to output logs to the console.

'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },

There are four elements of a logging configuration:

For our configuration we are only interested in the first two. The code above sets up our logging handler. We are declaring the console as a logging stream handler.

'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'),
        },
    },

Then finally we set up the logger itself, instruct it to utilise the 'console' handler, and set the minimum level of logging to 'ERROR'. This way we only see when things are actually wrong with our application, rather than logging all messages coming out of Django (the 'DEBUG' logging level).

For more information on Django logging see the documentation.

For more information on Heroku logging see their support centre.