首页 > 解决方案 > 禁用使用 Django 登录 gunicorn 以获取特定请求/URL/端点

问题描述

这个问题类似于Disable logging in gunicorn for a specific request/URL/endpoint除了我的问题是关于在 Django 应用程序中禁用 gunicorn 健康检查日志记录。

如何在 Django 应用程序中禁用 gunicorn 登录?

我也在使用系统日志,所以settings.LOGGING字典是这样的:

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False, 
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "default",
        }, 
        "syslog": {
            "level": "DEBUG",
            "class": "logging.handlers.SysLogHandler",
            "formatter": "default",
            "facility": SysLogHandler.LOG_LOCAL2,
            "address": syslog_address,
        },
    },
    "loggers": {
        "django": {"handlers": ["console", "syslog"], "propagate": True},
        "apps": {"handlers": ["console", "syslog"], "level": "DEBUG"},
        "utils": {"handlers": ["console", "syslog"], "level": "DEBUG"}, 
        "gunicorn.access": {"handlers": ["console", "syslog"], "level": "INFO"},
        "gunicorn.error": {"handlers": ["console", "syslog"], "level": "INFO"},
    },
}

请注意,我明确添加了gunicorn.access用于 syslog 的记录器(请参阅:https ://github.com/benoitc/gunicorn/issues/2016 )。

标签: djangogunicorn

解决方案


我在回答我自己的问题。

一旦我添加了gunicorn.access要处理的记录器syslog,我就不能简单地pre_request在我的文件中添加一个钩子gunicorn.conf(根据这个解决方案)。

您必须按照文档gunicorn.glogging.Logger中的说明通过子类化来提供您自己的自定义日志记录类。

创建一个日志模块并添加:

from gunicorn import glogging
class CustomGunicornLogger(glogging.Logger):
    def access(self, resp, req, environ, request_time):
        # disable healthcheck logging
        if req.path in ["/healthcheck"]:
            return
        super().access(resp, req, environ, request_time)

在您的gunicorn.conf文件中,添加:

logger_class = 'your_module.CustomGunicornLogger'

gunicorn.conf使用gunicorn 时使用您的文件:

gunicorn --config=gunicorn.conf your_django_app.wsgi:application

推荐阅读