#logging-tracing #spans #fields #json #structured #tracing-subscriber #events

tracing_json_span_fields

从追踪中获取字段的结构化 JSON 日志

2 个版本

0.1.1 2023年7月25日
0.1.0 2023年7月25日

#48#tracing-subscriber

MIT 许可证

29KB
609 代码行

使用来自追踪的 span 字段进行结构化 JSON 日志

tracing_subscriber 中的 JSON 支持不同,此实现将 span 作为提供上下文的一种方式,并将所有 span 的所有字段添加到日志事件中。

示例

use tracing::{info, info_span};
use tracing_subscriber::prelude::*;
use tracing_json_span_fields::JsonLayer;
tracing_subscriber::registry().with(JsonLayer::pretty()).init();
let _span = info_span!("A span", span_field = 42).entered();
info!(logged_message_field = "value", "Logged message");

将生成以下输出

{
  "log_level": "INFO",
  "logged_message_field": "value",
  "message": "Logged message",
  "name": "event src/main.rs:123",
  "span_field": 42,
  "target": "tracing_json",
  "timestamp": "2023-07-25T09:53:01.790152227Z"
}

自定义时间戳

use time::macros::format_description;
use tracing::{error, info_span};
use tracing_subscriber::prelude::*;
use tracing_json_span_fields::JsonLayer;
let timestamp_format = format_description!("[hour]:[minute]:[second].[subsecond digits:1]");
tracing_subscriber::registry().with(JsonLayer::default().with_timestamp_format(timestamp_format)).init();
let _span = info_span!("A span", span_field = 42).entered();
error!(logged_message_field = "value", "Logged message");

将生成以下输出

{"log_level":"ERROR","logged_message_field":"value","message":"Logged message","name":"event src/main.rs:123","span_field":42,"target":"tracing_json","timestamp":"10:02:01.9"}

感谢

另请参阅

依赖项

~3MB
~53K SLoC