April 3, 2025

Silencing Disallowed Host Errors in Django

A quick one today, that's more for my future reference, but it might help you! The DisallowedHost error is common in Django especially when standing up a new project. ALLOWED_HOSTS needs to be configured with valid hostnames for your application to work. This is good security practice as plenty of bots will hit your site when it goes live, and these errors typically end up in Sentry or some similar tool.

However, Sentry has limits and a log error like this can easily cause your monthly quota to explode (as it did last month for me), which prevents Sentry capturing actual bugs! There are a number of potential fixes to this:

  1. Configure LOGGING to not log the message (I tried and failed)
  2. Add some configuration to the webserver in front of Django (I wanted to minimise other changes and I don't care right now about the actual requests hitting Django, just the log message)
  3. Use a function from the Sentry SDK - This worked!

The code to ignore the log message in Sentry is as follows:

from sentry_sdk.integrations.logging import ignore_logger
ignore_logger("django.security.DisallowedHost")

That said I would be interested to know what is missing from this LOGGING configuration as this worked locally, but not when deployed. Please do let me know!

LOGGING = {
    "version": 1,
    "disable_existing_loggers": True,
    "formatters": {
        "verbose": {
            "format": "%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s",
        },
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "verbose",
        },
        "null": {
            "level": "DEBUG",
            "class": "logging.NullHandler",
            "formatter": "verbose",
        },
    },
    "root": {"level": "INFO", "handlers": ["console"]},
    "loggers": {
        "django.db.backends": {
            "level": "ERROR",
            "handlers": ["console"],
            "propagate": False,
        },
        
        "sentry_sdk": {"level": "ERROR", "handlers": ["console"], "propagate": False},
        "django.security.DisallowedHost": {
            "level": "ERROR",
            "handlers": ["null"],
            "propagate": False,
        },
    },
}