[Django]-Logging in Django and gunicorn

26👍

I have solved my problem. Providing the details so it might help somebody with similar issue.

Decided not to mix up with gunicorn and django logs and to create separate log file for django.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
        'logfile': {
            'level':'DEBUG',
            'class':'logging.FileHandler',
            'filename': BASE_DIR + "/../logfile",
        },
    },
    'root': {
        'level': 'INFO',
        'handlers': ['console', 'logfile']
    },
}

With this configuration every message written with severity >= INFO will be written to file “logfile” located just outside of source directory.

6👍

I’d like to add a 2021 answer for this, as server logs are so helpful and I couldn’t find the answer I was looking for without having to merge a couple of different examples. I’m using django==3.1 and gunicorn==20.0.4 in a Dockerized application that’s hosted on Heroku. I just wanted my Django server logs to show up both in my local stdout when I ran docker-compose up, and in papertrail logs on Heroku. This is working for me.

# In Dockerfile, I created a location for the logs, 
# and point there when starting gunicorn
RUN mkdir /logs
CMD gunicorn app.wsgi:application --bind 0.0.0.0:$PORT --workers 3 --capture-output --access-logfile /logs/gunicorn-access.log

Then in the Django settings, I used this for the logging_dict:

import logging.config
# Clear prev config
LOGGING_CONFIG = None
logging.config.dictConfig({
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            'format': '%(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'console',
        },
    },
    'loggers': {
        'gunicorn': { # this was what I was missing, I kept using django and not seeing any server logs
            'level': 'INFO',
            'handlers': ['console'],
            'propagate': True,
        },
    },

})

Leave a comment