python - 如何过滤gunicorn的日志?

标签 python logging gunicorn python-logging

我有一个带有gunicorn的Flask API。 Gunicorn 记录对我的 API 的所有请求,即

172.17.0.1 - - [19/Sep/2018:13:50:58 +0000] "GET/api/v1/myview HTTP/1.1"200 16 "-""Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36(KHTML,如 Gecko)Chrome/68.0.3440.106 Safari/537.36"

但是,我想过滤日志以排除从其他服务调用的某个端点几秒钟。

我编写了一个过滤器来排除此端点被记录:

class NoReadyFilter(logging.Filter):
    def filter(self, record):
        return record.getMessage().find('/api/v1/ready') == -1

如果我将此过滤器添加到 werkzeug 记录器并使用 Flask 开发服务器,则该过滤器可以工作。对 /api/v1/ready 的请求不会出现在日志文件中。但是,我似乎无法将过滤器添加到gunicorn记录器中。使用以下代码,对 /api/v1/ready 的请求仍然出现:

if __name__ != '__main__':
    gunicorn_logger = logging.getLogger('gunicorn.glogging.Logger')
    gunicorn_logger.setLevel(logging.INFO)
    gunicorn_logger.addFilter(NoReadyFilter())

如何向 Gunicorn 记录器添加过滤器?我尝试按照建议将其添加到 gunicorn.error-logger here ,但没有帮助。

最佳答案

我终于找到了一种通过创建子类来做到这一点的方法

class CustomGunicornLogger(glogging.Logger):

    def setup(self, cfg):
        super().setup(cfg)

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

继承自gunicorn.glogging.Logger。然后,您可以提供此类作为 gunicorn 的参数,例如

gunicorn --logger-class "myproject.CustomGunicornLogger" app

关于python - 如何过滤gunicorn的日志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52407736/

相关文章:

python - 覆盖类变量和并发 Flask 请求

python - 如何在 Python 中创建二维数组

function - 基本 Powershell 日志记录

logging - JBoss AS 6 日志模式

file - 使用 gradle 4 登录到文件

python - 为什么 gunicorn 显示这么多进程?

django - 错误请求 400 : nginx/gunicorn

python - 如果我们可以直接使用变量而无需初始化,为什么我们在tensorflow中使用tf.Variable?

python - 使用另一个数据框更新值

python - 如何将新列添加到按 groupby 分组的分层数据框中