django:如何为SuspiciousOperation异常创建自定义日志记录筛选器?

时间:2018-01-16 18:52:14

标签: django logging

迁移到1.11(从1.8开始)后,我从日志记录中收到一些SuspiciousOperation错误。

似乎它来自JS请求,如果用户移动鼠标,它会使会话保持活动状态。但这并不重要。

如何过滤此异常?

我尝试了什么:

我刚刚在某处创建了一个过滤器:

import logging

from django.core.exceptions import SuspiciousOperation

class StopSuspiciousOperation(logging.Filter):
    def filter(self, record):
        if record.exc_info:
            exc_value = record.exc_info[1]
            return isinstance(exc_value, SuspiciousOperation)
        return True

然后我将此过滤器添加到我的配置中:

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

但我仍然收到错误:

内部服务器错误:/ keepalive

SuspiciousOperation at /keepalive
The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example.

Request Method: GET
Request URL: https://XXXXXX/YYYYYY
Django Version: 1.11.9
Python Executable: /usr/bin/python
Python Version: 2.7.3

1 个答案:

答案 0 :(得分:0)

我不确定正确的答案,但是我认为django正在WSGI级别捕获SuspiciousOperation并记录了一个错误。看到: https://docs.djangoproject.com/en/dev/ref/exceptions/#suspiciousoperation

  

如果SuspiciousOperation异常达到WSGI处理程序级别,则它   在错误级别记录日志,并导致HttpResponseBadRequest。

您可能只想过滤出这样的错误请求:

from logging import LogRecord


def filter_400(record: LogRecord) -> bool:
    '''Filter out HTTP Error Code 400 Bad Request'''
    return record.status_code != 400