【问题标题】:How to exclude 404 error messages from logging to email?如何从记录到电子邮件中排除 404 错误消息?
【发布时间】:2022-09-27 17:39:45
【问题描述】:

下午好。我在设置中有这种类型的日志:

LOGGING = {
    \'version\': 1,
    \'disable_existing_loggers\': False,
    \'filters\': {
        \'require_debug_false\': {
            \'()\': \'django.utils.log.RequireDebugFalse\'
        }
    },

    \'formatters\': {
        \'verbose\': {
            \'format\': \'{levelname} {asctime} {module} {process:d} {thread:d} {message}\',
            \'style\': \'{\',
        },
        \'simple\': {
            \'format\': \'{levelname} {message}\',
            \'style\': \'{\',
        },
    },

    \'handlers\': {
        \'console\': {
            \'level\': \'INFO\',
            \'class\': \'logging.StreamHandler\',
        },

        \'mail_admins\': {
            \'level\': \'WARNING\',
            \'filters\': [\'require_debug_false\'],
            \'class\': \'django.utils.log.AdminEmailHandler\',
            \'include_html\': True,
        },
    },

    \'loggers\': {
        \'\': {
            \'handlers\': [\'console\', \'mail_admins\'],
            \'level\': \'DEBUG\',
            \'propagate\': False,
        },
    }
}

我在电子邮件中收到所有警告及以上级别的消息。 由于各种机器人、垃圾邮件发送者或其他用户在寻找隐藏的文件和文件夹,我收到很多 404(找不到页面)错误消息。

如何停止接收有关 404 错误的信息?

    标签: django


    【解决方案1】:

    这要感谢 mail_admins 处理程序,它通过电子邮件向您发送任何警告级别及以上错误,see doc

    正如文档中所建议的,您可以将此处理程序子类化并改用新的自定义处理程序。

    class MyCustomHandler(AdminEmailHandler):
        """Custom Handler that ignores 404 errors instead of sending them by email"""
        def handle(self, record):
            if record.exc_info:
                exc_type, exc_value, tb = record.exc_info
                if isinstance(exc_value, Http404):
                    return
            super().handle(record)
    

    【讨论】:

    • 是的,我试图弄清楚这个类,但我就是不知道如何在 emit 方法中获取响应代码以便只排除 404 页面
    • 我用一个例子编辑了评论,让我知道它是否适合你。
    猜你喜欢
    • 2011-10-19
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2018-05-18
    • 2013-02-18
    • 1970-01-01
    • 2020-01-04
    • 2011-04-18
    相关资源
    最近更新 更多