Logging to Stdout with Django

Logging to Stdout with Django

May 23, 2020

Logging is one of the most important tools when troubleshooting and debugging a Django application.

If you're following the Twelve-Factor App methodology for your application, then you'll want to send your logs to Stdout.
The Django documentation doesn't provide an example of how to do this easily so let's go through how to achieve that.

In your Django 'settings.py' add the following configuration.

import logging
import sys

LOGGING = {
   'version': 1,
   'disable_existing_loggers': False,
   'formatters': {
       'verbose': {
           'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
       },
   },
   'handlers': {
       'console': {
           'level': 'INFO',
           'class': 'logging.StreamHandler',
           'stream': sys.stdout,
           'formatter': 'verbose'
       },
   },
   'loggers': {
       '': {
           'handlers': ['console'],
           'level': 'INFO',
           'propagate': True,
       },
   },
}

This will result in all logs of info level or above going to Stdout. It's as easy as that.

Next, of course, you'll want a centralised place to read your logs. We use papertrail for this. Here are some useful links for that:

- How to send your Docker logs to papertrail
- How to send your Django logs directly to papertrail. (Note that this method goes against the Twelve-Factor App methodology)

If you have any other tips or tricks to share, we'd love to hear them in the comments!

Latest Articles

How to validate Django ImageField dimensions
How to use ipdb debugger with docker-compose
How to rename an existing Django application, the right way