Django – Logging to File and Sending Emails when Exceptions Occurs

Categories Django, Python

Logging in any application is an important aspect of application design. Making sure that all errors/exceptions get logged in production help in finding issues. In this article, I am going to show how to do logging in a Django application.

Django usages python’s logging module for logging.  Logging configuration in python consists of 4 parts- Loggers, Handlers, Filters, Formatters. You can read more about these in Django documentation, but here is quick overview:

Formatters – As the name suggests, this describes the format of log text.

Filters – Filters can be used to filter out log records or to modify log records before they are logged.

Handlers – Handlers determine what happens to the log message. Log message can be written to file, printed on the screen,  emailed etc.

Loggers – Loggers are the entry point for logging. Here you define the handlers for the log, level of logging etc.

To configure logging in Django, a configuration dictionary needs to be provided to Django’s LOGGING settings.

Here is a sample configuration which logs to file and also sends emails to admins:

ADMINS = (('Harshveer', 'harshveer1889@gmail.com'), ('Harshveer', 'admin@harshveers.com'))
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {

    },
    'handlers': {
		'file': {
            'level': 'WARNING',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, "pyserver.log"),
			'formatter': 'verbose'
        },
        'mail_admins': {
            'level': 'WARNING',
            'class': 'django.utils.log.AdminEmailHandler',
            'formatter': 'verbose'
        }
    },
    'loggers': {
        'django': {
            'handlers': ['file', 'mail_admins'],
            'propagate': True,
            'level': 'WARNING',
        },
        'LoggerApp': {
            'handlers': ['file', 'mail_admins'],
            'propagate': True,
            'level': 'WARNING',
        }
    }
}

Now whenever an exception occurs in LoggerApp or django app, it will be logged to pyserver.log and also an email will be sent to users defined in ADMINS setting.

To log message manually logging module can be used as below:

from django.http import HttpResponse
import logging

# Get an instance of a logger
logger = logging.getLogger(__name__)

def log_error(request):
	logger.error('This is the manual error logging.')
	return HttpResponse("Logged manual error.")

That’s all about configuring logging in Django app. You can find complete project code for this on GitHub.

If you liked the post or have any suggestions, leave a comment 🙂

No Comments

Leave a Reply

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