How to Add Logger in Django – Simple Log to File in Django

Go to the setting file (settings.py) of your Django project and add these lines of code at the bottom.

LOG_FILE_NAME = BASE_DIR + '/logs/' + str(date.today()) + '.txt'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': LOG_FILE_NAME,
            'maxBytes': 1024 * 1024 * 5,
            'backupCount': 5,
            'formatter': 'standard',
        },
        'request_handler': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': LOG_FILE_NAME,
            'maxBytes': 1024 * 1024 * 5,
            'backupCount': 5,
            'formatter': 'standard',
        },
    },
    'loggers': {
        '': {
            'handlers': ['default'],
            'level': 'DEBUG',
            'propagate': True
        },
        'django.request': {
            'handlers': ['request_handler'],
            'level': 'DEBUG',
            'propagate': False
        },
    }
}

Put this at the top of the files (views.py) where you want to add logger.

import logging

logger = logging.getLogger(__name__)

To log errors use

log.debug(“Debugging”)

log.info(“Info”)

log.warn(“Warning”)

log.error(“Errors”)

For example, if you want to log exception.

try:

# Causing errors

except Exception as e:

logger.error(e)

If you want a separate log file everyday to ease searching for errors in log file then add this line of code in settings.py file.

from datetime import date

Then modify the LOG_FILE_NAME as below.

LOG_FILE_NAME = BASE_DIR + ‘/logs/’ + str(date.today()) + ‘.txt’

Create a folder called “logs” in the same directory where you have manage.py. Otherwise you’ll get errors.

This is going to create files every day and the current date (YYYY-MM-DD.txt) will be the file name.

Note: Do not use this logger for Django if you are using Apache server.

2 Comments

Vignesh · October 11, 2018 at 5:34 AM

Thanks. Really helpfull.

Vivek · April 29, 2019 at 9:06 AM

Straight to the point. Helpful and clean. Thanks for the article. Will stay tuned to your blog.

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *