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

Kri*_*per 5 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)
...
Run Code Online (Sandbox Code Playgroud)

配置 Gunicorn 以对其错误日志使用一致格式的最佳方法是什么?

ara*_*aki 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
Run Code Online (Sandbox Code Playgroud)

关键是覆盖gunicorn.error记录器配置,上面的片段正是这样做的。

请注意该propagate=0字段,这一点很重要,否则您的日志消息将被打印两次(gunicorn 始终保留默认的日志配置)。