禁止使用Django登录针对特定请求/ URL /端点的gunicorn

时间:2019-11-12 10:06:40

标签: django gunicorn

此问题与Disable logging in gunicorn for a specific request / URL / endpoint相似,除了我的问题与在Django应用中禁用gunicorn运行状况检查日志记录有关。

如何禁用Django应用中的gunicorn日志记录?

我也在使用syslog,因此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记录器以用于sy​​slog(请参阅:https://github.com/benoitc/gunicorn/issues/2016)。

2 个答案:

答案 0 :(得分:1)

我在回答自己的问题。

一旦我添加了gunicorn.access记录程序以处理syslog,我就不能简单地在我的pre_request文件中添加一个gunicorn.conf钩子(按照this solution )。

您必须按照docs所述,通过将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时,请使用您的gunicorn.conf文件:

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

答案 1 :(得分:1)

另一个解决方案的灵感来自gunicorn的答案:How to filter logs from gunicorn?

class HealthCheckFilter(logging.Filter):
    def filter(self, record):
        return record.getMessage().find('/healthcheck') == -1

将运行状况检查添加到自定义记录器:

class CustomGunicornLogger(glogging.Logger):
    def setup(self, cfg):
        super().setup(cfg)

        # Add filters to Gunicorn logger
        logger = logging.getLogger("gunicorn.access")
        logger.addFilter(HealthCheckFilter())