Skip to main content

tdm_server_rust/telemetry/skywalking/
local_layer.rs

1//! tracing #[instrument] → SkyWalking LocalSpan 桥接
2
3use super::context;
4use ::skywalking::trace::span::Span;
5use tracing::{Id, Subscriber};
6use tracing_subscriber::layer::Context;
7use tracing_subscriber::Layer;
8
9/// SW LocalSpan 生命周期守卫(Drop 时结束 span)
10#[allow(dead_code)]
11struct SwLocalGuard(Span);
12
13/// 将 tracing span 映射为 SW LocalSpan(仅在 HTTP Entry 上下文内生效)
14pub struct SkyWalkingLocalLayer;
15
16impl<S> Layer<S> for SkyWalkingLocalLayer
17where
18    S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
19{
20    fn on_enter(&self, id: &Id, ctx: Context<'_, S>) {
21        if !context::is_in_request_context() {
22            return;
23        }
24        let Some(meta) = ctx.metadata(id) else {
25            return;
26        };
27        if meta.name() == "http.request" {
28            return;
29        }
30        let op = meta.name();
31        if let Some(sw_span) = context::create_local_span(op) {
32            if let Some(span) = ctx.span(id) {
33                span.extensions_mut().insert(SwLocalGuard(sw_span));
34            }
35        }
36    }
37
38    fn on_exit(&self, id: &Id, ctx: Context<'_, S>) {
39        if let Some(span) = ctx.span(id) {
40            span.extensions_mut().remove::<SwLocalGuard>();
41        }
42    }
43}