[英]How to add a timestamp and loglevel to each log in Python's structlog?
How to configure structlog
so it automatically adds loglevel
and a timestamp
(and maybe other fields) by default to each log message it logs?如何配置
structlog
以便它在默认情况下自动将日志loglevel
和timestamp
(可能还有其他字段)添加到它记录的每条日志消息中? So I do not have to add it to every message explicitly.所以我不必将它明确地添加到每条消息中。
I am displaying my messages as JSON (for further processing with Fluentd, Elasticsearch and Kibana).我将我的消息显示为 JSON(用于进一步处理 Fluentd、Elasticsearch 和 Kibana)。
loglevel
is not (for some reason) included in the output JSON log. loglevel
没有(出于某种原因)包含在 output JSON 日志中。
That is how I confiure my structlog
.这就是我确认
structlog
的方式。
structlog.configure(
processors=[structlog.processors.JSONRenderer()],
wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
)
I am logging:我正在记录:
log.info("Artist saved", spotify_id=id)
Logs I am seeing (mind no time
and no loglevel
):我看到的日志(不要介意
time
和日志loglevel
):
{"logger": "get_artists.py", "spotify_id": "4Y6z2aIww27vnxZz9xfG3S", "event": "Artist saved"}
I found my answer here: Python add extra fields to structlog-based formatters within logging我在这里找到了答案: Python add extra fields to structlog-based formatters within logging
There are processors that are doing exactly what I needed:有些处理器正在做我需要的事情:
structlog.configure(
processors=[
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso", key="ts"),
structlog.processors.JSONRenderer(),
],
wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
)
Adding both, add_log_level
and TimeStamper
resulted, as expected in the extra fields in the log ..., "level": "info", "ts": "2022-04-17T19:21:56.426093Z"}
.添加
add_log_level
和TimeStamper
结果,正如在日志中的额外字段中预期的那样..., "level": "info", "ts": "2022-04-17T19:21:56.426093Z"}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.