[Django]-Django (CSRF token missing or incorrect) suppress logging

4👍

As per official django documentation you can update your LOGGING settings this:

'handlers': {
    'null': {
        'class': 'logging.NullHandler',
    },
},
'loggers': {
    'django.security.csrf': {
        'handlers': ['null'],
        'propagate': False,
    },
},
👤ruddra

4👍

If you only want to suppress this particular error, but still log other CSRF-related errors, it gets a bit tricky.

The CSRF module uses the logger named django.security.csrf. The message is logged in the _reject method of the CsrfViewMiddleware. You could add a filter to that logger that filters out log records with that error reason in the args. That would look something like this:

from django.middleware.csrf import REASON_BAD_TOKEN

def missing_token_filter(record):
    return REASON_BAD_TOKEN not in record.args

LOGGING = {
   ...,
   'handlers': {
       ...
       'django.security.csrf': {
           'filters': ['missing_token_filter']
       }
   },
   'filters': {
       ...,
       'missing_token_filter: {
           '()': 'path.to.missing_token_filter',
       },
}

Leave a comment