Receive Email Notification on Server Error in Django

Django provides an excellent built-in feature of sending email to the administrator whenever a server error occurs. The email is sent to the users listed in ADMINS variables whenever your code raises an unhandled exception and results in an internal server error (HTTP status code 500). 

Emails are sent via. Django’s logging framework. The default LOGGING configuration is enough to receive email which looks similar to code below:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

You need to define a few variables in settings.py to make sure you receive email. 

Define SERVER_EMAIL and ADMINS variable

Define name and email of all your administrator in ADMINS variable as a tuple. 

ADMINS = (('John', 'john@example.com'), ('Mary', 'mary@example.com'))

Also make sure that you have defined SERVER_EMAIL variable. Otherwise, the mail will be sent via. root@localhost and your mail client may block it.

SERVER_EMAIL = 'info@mysite.com'

With your default settings, you will now receive email as well as complete log on your email.

You can also receive email on 404 errors. I usually avoid this as it would flood my email. Complete details can be found on Django’s official page on error reporting.

Written on August 19, 2014