过滤掉特定的Python日志消息

时间:2014-12-19 23:52:22

标签: python django

是否可以阻止将特定邮件写入 Django日志文件?我已经阅读了Django记录器文档,他们只是解决 过滤Django类的错误。

我想阻止写入我的日志文件的错误是:

[19/Dec/2014 12:21:21] INFO [requests.packages.urllib3.connectionpool:171] Starting new HTTP connection (1): api.wurflcloud.com

我的Django日志配置如下所示。

由于

# settings.py
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': {
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'logfile': {
            'level':LOG_LEVEL,
            'class':'logging.handlers.RotatingFileHandler',
            'filename': '/var/log/myproj/myproj.log',
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
        },
        'database_logfile': {
            'level':LOG_LEVEL,
            'class':'logging.handlers.RotatingFileHandler',
            'filename': '/var/log/myproj/database.log',
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
        },
        'console':{
            'level':LOG_LEVEL,
            'class':'logging.StreamHandler',
            'formatter': 'standard'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
            # Only send emails when DEBUG = False
            #'filters': ['require_debug_false'],
        },
    },
    'loggers': {
        'django': {
            'handlers':['console'],
            'propagate': True,
            'level':'WARN',
        },
        'django.request': {
           'handlers': ['mail_admins'],
           'level': 'ERROR',
           'propagate': False,
        },
        'django.db.backends': {
            'handlers': ['database_logfile'],
            'level': 'DEBUG',
            'propagate': False,
        },
        '': {
            'handlers': ['console', 'logfile', 'mail_admins'],
            'level': 'DEBUG',
        },
    }
}

1 个答案:

答案 0 :(得分:0)

Python logging包不支持按消息内容进行过滤,只支持消息记录器和消息级别。

解决问题的两种可能方法是

  • 对违规函数进行补丁,并将其替换为您自己的版本,该版本不会生成给定的消息(requests.packages.urllib3.connectionpool处的函数:171)

  • 编写自己的日志记录处理程序,可以按内容处理过滤日志消息(非常严厉的方法只是为了删除一条消息)

同样作为长期解决方案,您可以尝试

  • requests软件包社区进行沟通,解释您的问题,寻求合作并编写修补程序以修复库,以便在将来的版本中可以轻松删除特定邮件