我有一个带有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/