使用Django配置和使用structlog

时间:2017-05-08 19:10:32

标签: django python-3.x logging configuration

有人和Django一起使用structlog吗?我正在寻找代码示例如何集成Django日志记录(通过标准库完成)和structlog。

我尝试了"Rendering Using structlog-based Formatters Within logging"示例中的代码,只做了最轻微的修改:

# From my settings.py, basically the same code as in the linked example

timestamper = structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S")
pre_chain = [
    structlog.stdlib.add_log_level,
    timestamper,
]
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": { ... },  # Exactly like in the linked example
    "handlers": { ... },    # Ditto, but only "default" handler (no files)
    "loggers": {
        "django": {
            "handlers": ["default"],
            "level": "INFO",
        },
        # I also had "" logger here, with the same config as "django",
        # but it's irrelevant for the example purposes.
    }
}
# Same as in the example
structlog.configure(
    processors=[
        structlog.stdlib.add_log_level,
        structlog.stdlib.PositionalArgumentsFormatter(),
        timestamper,
        structlog.processors.StackInfoRenderer(),
        structlog.processors.format_exc_info,
        structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
    ],
    context_class=dict,
    logger_factory=structlog.stdlib.LoggerFactory(),
    wrapper_class=structlog.stdlib.BoundLogger,
    cache_logger_on_first_use=True,
)

但是,我最终遇到了记录错误。这是一个以404结尾的简单GET请求发生的事件的摘录

TypeError: not all arguments converted during string formatting
...
  File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 152, in get_response
    extra={'status_code': 404, 'request': request},
Message: '\x1b[2m2017-05-08 18:34:53\x1b[0m [\x1b[33m\x1b[1mwarning  \x1b[0m] \x1b[1mNot Found: /favicon.ico\x1b[0m'
Arguments: ('/favicon.ico',)

我试图找出究竟发生了什么,但在调试器中迷失了方向。

当然,我只能将structlog用于应用程序日志记录,并保留标准库记录器。但是,我希望所有日志记录统一,因此我的应用程序的输出将是统一的,可以进行解析。

我非常感谢一段代码片段,其中展示了如何正确地将structlog与Django集成。

1 个答案:

答案 0 :(得分:6)

这个bug很可能会在structlog 17.2中修复,应该很快发布:https://github.com/hynek/structlog/pull/117(如果能解决你的问题,请随时发表评论或试用)。