You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用内置json tracing subscriber将level字段重命名为severity?

如何将tracing JSON输出中的"level"字段重命名为"severity"?

你提到的tracing_subscriber默认JSON输出里的level字段重命名需求,不能用fmt::format::debug_fn来实现——因为debug_fn是用来自定义日志消息的文本格式,而非修改JSON结构里的字段名。正确的做法是通过JSON格式化器的字段映射功能来实现:

解决方案代码示例

use tracing_subscriber::fmt::format::Json;
use tracing_subscriber::prelude::*;

fn main() {
    // 自定义JSON格式化器,重命名level字段为severity
    let json_formatter = Json::new()
        .flatten_event(true)
        .map_event_fields(|mut fields| {
            if let Some(level_value) = fields.remove("level") {
                fields.insert("severity", level_value);
            }
            fields
        });

    tracing_subscriber::fmt()
        .event_format(json_formatter)
        .with_max_level(tracing::Level::DEBUG)
        .init();

    tracing::debug!("This is a debug message");
}

输出效果

运行后会得到如下JSON输出:

{"timestamp":"2023-07-14T20:47:29.302872Z","severity":"DEBUG","message":"This is a debug message","target":"publisher"}

原理说明

  • Json::map_event_fields方法允许我们对事件的字段集合进行修改:先移除默认的level字段,再将对应的值插入为severity字段。
  • 这种方式完全适配JSON格式化器的逻辑,不会像debug_fn那样出现兼容性问题,因为debug_fn是针对文本日志格式设计的接口。

内容的提问来源于stack exchange,提问作者VBar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 21:09:53