django - 通过 Django 配置和使用 structlog

标签 django python-3.x logging configuration

有人用structlog吗?与 Django ?我正在寻找一个代码示例,如何集成 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 正确集成的代码片段。

最佳答案

这个错误很可能会在 structlog 17.2 中得到修复,并且应该很快发布:https://github.com/hynek/structlog/pull/117 (请随意发表评论或尝试是否可以解决您的问题)。

关于django - 通过 Django 配置和使用 structlog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43855507/

相关文章:

python - Django 列表在 View 之间不会被破坏

python lxml 3.3.5 - 加载代码时出错 - "ValueError: lxml.etree._Element has the wrong size, try recompiling"

python - 理解gensim word2vec的most_similar

python - 在 Pandas 中按升序和降序有条件地对单个列进行排序

python - python 3中类 'bytes'的不同表示

在本地记录 Azure Service Fabric 服务

django - 使用 Wagtail API 从页面 slug 返回所有字段

python - 使用后台线程定期刷新字段的值

ms-access - Showplan.out 在安装了 MS-Access 2003 和多个版本的 Office 的 Windows 7 中?

python - 如何以编程方式告诉 Celery 将所有日志消息发送到 stdout 或 stderr?