Search code examples
pythondjangoslack

How does django know when a 500 or related server error occurs?


I know that django sends mail to the users in the admin list, but I want to know how django itself gets notified about the error. I am searching something like:

if 500 error occurs:
    send slack message
    ...

I have no problem integrating with slack, but I don't know how to get that if condition. I have read about the logging but didn't find anything relevant.

Here are my logging settings:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt': "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(os.path.join(BASE_DIR, 'econnect-local.log')),
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'xhtml2pdf': {
            'handlers': ['file'],
            'level': 'DEBUG'
        },
    },
}

Maybe I'm missing something stupid. Thanks for your help.


Solution

  • This doesn't look like something you should do in the logging settings, but rather use middleware and the process_exception() method. This function will fire whenever there's an error caught by the view, and it will have access to the error that was raised, for you to handle however you'd like.

    (Found on a related answer here)