可以使用Pythons标准库完成结构化日志记录吗? [英] Can structured logging be done with Pythons standard library?

查看:72
本文介绍了可以使用Pythons标准库完成结构化日志记录吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读了有关结构化日志的信息(此处).这个想法似乎不是通过将简单的字符串作为一行添加到日志文件中来进行记录,而是通过JSON对象进行记录.这样就可以通过自动工具分析日志文件.

I recently read about structured logging (here). The idea seems to be to log not by appending simple strings as a line to a logfile, but instead JSON objects. This makes it possible to analyze the logfile by automatic tools.

Pythons logging库可以进行结构化日志记录吗?如果不是,是否有主流"解决方案(例如numpy/scipy是科学计算的主流解决方案)?我发现了 structlog ,但是我不确定它的普及程度.

Can Pythons logging library do structured logging? If not, is there a "mainstream" solution for it (e.g. like numpy/scipy is the mainstream solution for scientific calculations)? I found structlog, but I'm not sure how widespread it is.

推荐答案

如果安装 (288星,70个分支),并具有如下所示的日志记录配置(YAML),您将获得结构化的日志记录文件.

If you install python-json-logger (288 stars, 70 forks) and have a logging configuration (YAML) like the following, you will get a structured logging file.

version: 1
formatters:
    detailed:
        class: logging.Formatter
        format: '[%(asctime)s]:[%(levelname)s]: %(message)s'
    json:
        class: pythonjsonlogger.jsonlogger.JsonFormatter
        format: '%(asctime)s %(levelname)s %(message)s'
handlers:
    console:
        class: logging.StreamHandler
        level: INFO
        formatter: detailed
    file:
        class: logging.FileHandler
        filename: logfile.log
        level: DEBUG
        formatter: json
root:
    level: DEBUG
    handlers:
        - console
        - file

例外

您可能还想使异常/回溯使用结构化格式.

Exceptions

You might also want to make exceptions / tracebacks use the structured format.

请参见我可以在一行中/通过日志记录来使Python输出异常吗?

这篇关于可以使用Pythons标准库完成结构化日志记录吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆