我该如何配置gunicorn以使用一致的错误日志格式?

7

我正在使用Gunicorn来部署Python Flask应用程序。在运行gunicorn时,可以使用--access-log-format命令行参数配置访问日志格式。但我无法弄清如何配置错误日志。

我可以接受默认格式,但它不一致。看起来Gunicorn状态消息有一个格式,而应用程序异常有另一种格式。这使得使用日志聚合变得困难。

例如,下面是来自Gunicorn错误日志的几条消息。前几行与异常行具有不同的格式。甚至日期时间格式也不同。

[2017-07-13 16:33:24 +0000] [15] [INFO] Booting worker with pid: 15
[2017-07-13 16:33:24 +0000] [16] [INFO] Booting worker with pid: 16
[2017-07-13 16:33:24 +0000] [17] [INFO] Booting worker with pid: 17
[2017-07-13 16:33:24 +0000] [18] [INFO] Booting worker with pid: 18
[2017-07-13 18:31:11,580] ERROR in app: Exception on /api/users [POST]
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
...

什么是将Gunicorn配置为使用一致格式的错误日志的最佳方法?
1个回答

6
使用此日志配置文件,我能够更改错误日志格式。
[loggers]
keys=root, gunicorn.error

[handlers]
keys=error_console

[formatters]
keys=generic

[logger_root]
level=INFO
handlers=error_console

[logger_gunicorn.error]
level=INFO
handlers=error_console
propagate=0
qualname=gunicorn.error

[handler_error_console]
class=StreamHandler
formatter=generic
args=(sys.stderr, )

[formatter_generic]
format=%(asctime)s %(levelname)-5s [%(module)s] ~ %(message)s
datefmt=%Y-%m-%d %H:%M:%S %Z
class=logging.Formatter

关键是覆盖gunicorn.error记录器的配置,上面的代码片段正是这样做的。
注意propagate=0字段,它很重要,否则您的日志消息将被打印两次(gunicorn始终保留默认的日志记录配置)。

1
关于使用的说明,我仍然需要指定 errorlog = 'gunicorn-error.log' 并使用以下命令运行 - gunicorn wsgi:application --config ../deploy/gunicorn.conf --log-config ../deploy/gunicorn-log.conf - radtek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接