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

时间:2017-07-13 18:46:02

标签: python logging gunicorn

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

我会使用默认格式,但它不一致。看起来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 个答案:

答案 0 :(得分:0)

使用此日志记录配置文件,我能够更改错误日志格式

[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始终保留默认的日志配置)。