Flask 0.10的default debug log format是
debug_log_format =
'-------------------------------------------------------------------------\n%
%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s
\n-------------------------------------------------------------------------'
如何将其更改为:
'-------------------------------------------------------------------------\n%
work_id %(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s
\n-------------------------------------------------------------------------'
其中 work_id
是每个请求的随机生成的UUID .
如果 Logger 是我自己创建的,我可以使用 logging.LoggerAdapter
并提供额外的信息作为dict {'work_id': some_uuid}
,然后我可以使用 record.work_id
在日志记录中访问它 .
但是 app.logger
是由create_logger() in Flask'slogging.py创建的,我是否必须修改Flask源来实现我想要的?
我还想过用我自己的 Logger 覆盖 app.logger
,比如 app.logger = my_logger
,它似乎不对 .
2 回答
Via Flask.debug_log_format
这样做:
例:
Via Handler and Formatter of standard logging module
Flask以任何方式使用日志记录,因此您可以使用logging.Handler和logging.Formatter来实现Flask外部 . 可以找到一个通用示例here . 日志配置的高级主题可以在the doc和cookbook中找到
针对您的问题的定制示例是:
Via overriding logging.Logger class
通过覆盖默认 Logger 类可以实现相同的目标 . 结合flask request context stack,您将能够在日志中获得自己的字段:
这是使用自定义
Formatter
的另一个示例 . 感谢@chfw和this我喜欢在这里使用
flask.has_request_context()
,因此日志记录不会妨碍单元测试