Search code examples
djangologginghttp-status-code-503

Django: Is there a way to filter out 503 'service unavilable' responses from mail_admins log handler?


I have django LOGGING configured with standard "mail admins on 500 errors":

'mail_admins': {
    'level': 'ERROR',
    'filters': ['require_debug_false'],
    'class': 'django.utils.log.AdminEmailHandler'
},

When I put site into maintenance mode (django-maintenance-mode), it correctly responds with 503 "Service Unavailable" for anonymous requests. This causes a barrage of emails to admins when the site is in maintenance mode. I want to "filter out 503 response IF site is in maintenance mode" to stem the flood. But can't see a simple way to do this (e.g., logging filter would need request to check if site in maintenance mode)

I know I could change the maintenance error code to a 400-level error, but that seems like non-semantic hack. Could also suspend admin emails during maintenance, but that requires remember to hack / revert settings file. Hoping someone has a clever idea how to achieve this simply, no hacks.


Solution

  • You can simply create filter 'require_not_maintenance_mode_503' in LOGGING of your settings.py and add the filter in handlers 'mail_admins'. This will prevent sending email on 503 error. For example:

        LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'filters': {
            'require_not_maintenance_mode_503': {
                '()': 'maintenance_mode.logging.RequireNotMaintenanceMode503',
            },
        },
        'formatters': {
            'verbose': {
                'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
            },
            'simple': {
                'format': '%(levelname)s %(message)s'
            },
        },
        'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'class': 'django.utils.log.AdminEmailHandler',
                'filters': ['require_not_maintenance_mode_503'],
                'formatter': 'simple'
            },
        },
        'loggers': {
            'django': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True,
            },
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True,
            },
        },
    }