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

Rust tracing未生成Span ID及关联父Span问题排查

解决tracing Span无ID、无法关联父Span的问题

要让Span自动生成ID、关联父Span并在日志中显示ID,只需修改tracing_subscriber的配置,启用Span ID和Trace ID的显示即可:

修复后的Subscriber配置

use tracing_subscriber::{fmt, registry, util::SubscriberInitExt};
use tracing_subscriber::level_filters::LevelFilter;
use tracing::Level;

let subscriber = registry()
    .with(
        fmt::layer()
            .compact()
            .with_file(true)
            .with_line_number(true)
            .with_span_events(fmt::FmtSpan::CLOSE)
            .with_target(false)
            // 启用Span ID和Trace ID的显示
            .with_format(fmt::format().with_span_ids(true).with_trace_ids(true))
            .with_filter(LevelFilter::from_level(Level::DEBUG))
    );

subscriber.init();

关键改动说明

  • 添加.with_format(fmt::format().with_span_ids(true).with_trace_ids(true)):该配置会让日志输出包含当前Span的ID(span_id)和整个调用链的Trace ID(trace_id),tracing会自动处理父子Span的关联——子Span会继承父Span的Trace ID,并关联父Span的ID。
  • 无需修改#[tracing::instrument]宏的使用:该宏会自动将当前Span关联到父Span,只要Subscriber配置正确,父子关联逻辑会自动生效。

依赖版本要求

确保Cargo.toml中tracing-subscriber的版本为0.3.x及以上:

[dependencies]
tracing = "0.1"
tracing-subscriber = "0.3"

修复后的日志示例

修复后,日志会包含类似以下的ID字段:

2024-06-23T12:37:08.371471Z DEBUG trace_id=0xabc123 span_id=0xdef456 get_or_list_prefix:get_item:root:outer_child: src/routes/get.rs:74: close time.busy=5.38µs time.idle=5.71µs key_prefix=Some("a") ...

其中trace_id在整个调用链中保持一致,span_id标识当前Span,通过这两个ID可以轻松关联父子Span的调用关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 21:55:07