Skip to main content

a2a_protocol_server/otel/telemetry/
subscriber.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! The `tracing` side of [`Telemetry`]: the layer that turns spans and events
5//! into OpenTelemetry spans and log records, and the subscriber
6//! `install_subscriber` installs with it.
7
8use opentelemetry::trace::TracerProvider as _;
9use tracing_subscriber::Layer;
10use tracing_subscriber::registry::LookupSpan;
11
12use super::{SCOPE, Telemetry, diagnostics, is_self_target};
13
14impl Telemetry {
15    /// The `tracing` layer: spans become OpenTelemetry spans, and events at
16    /// or above the log level become log records. Add it to the
17    /// application's subscriber, next to any other layers. A signal that is
18    /// off contributes nothing.
19    #[must_use]
20    pub fn layer<S>(&self) -> impl Layer<S> + Send + Sync + 'static
21    where
22        S: tracing::Subscriber + for<'a> LookupSpan<'a> + Send + Sync,
23    {
24        use tracing_subscriber::filter::filter_fn;
25        use tracing_subscriber::layer::Identity;
26        // A signal that is off contributes `Identity`, never `None`:
27        // `Option<Layer>::max_level_hint` is `OFF` for `None`
28        // (tracing-subscriber 0.3.23, `layer/mod.rs`), and combined with the
29        // other half that switched every span off process-wide — traces with
30        // logs off (the Langfuse preset) recorded nothing.
31        use tracing_subscriber::filter::LevelFilter;
32        // Each filter states its most verbose level (`with_max_level_hint`),
33        // so `tracing` disables the callsites below every layer's level at
34        // once instead of asking these closures for each event.
35        let span_level = self.span_level;
36        let spans: Box<dyn Layer<S> + Send + Sync> = match &self.tracer {
37            Some(provider) => Box::new(
38                tracing_opentelemetry::layer()
39                    .with_tracer(provider.tracer(SCOPE))
40                    .with_filter(
41                        filter_fn(move |meta| {
42                            *meta.level() <= span_level && !is_self_target(meta.target())
43                        })
44                        .with_max_level_hint(LevelFilter::from_level(span_level)),
45                    ),
46            ),
47            None => Box::new(Identity::new()),
48        };
49        let level = self.log_level;
50        let logs: Box<dyn Layer<S> + Send + Sync> = match &self.logger {
51            Some(provider) => Box::new(
52                opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge::new(provider)
53                    .with_filter(
54                        filter_fn(move |meta| {
55                            meta.is_event()
56                                && *meta.level() <= level
57                                && !is_self_target(meta.target())
58                        })
59                        .with_max_level_hint(LevelFilter::from_level(level)),
60                    ),
61            ),
62            None => Box::new(Identity::new()),
63        };
64        spans.and_then(logs)
65    }
66
67    /// Installs [`layer`](Self::layer) as the process's global `tracing`
68    /// subscriber, with a layer that prints warnings and errors to standard
69    /// error and logs [`describe`](Self::describe) once — what a binary with
70    /// no subscriber of its own needs. Without the printing layer a process
71    /// whose export is failing, or that was never given a collector, shows
72    /// nothing at all.
73    ///
74    /// `RUST_LOG` sets what is printed, in `target=level` form (default: `warn`
75    /// everywhere, `info` for this module's own startup line and for the
76    /// application's own crate, named after the default service name with `-`
77    /// as `_`: `with_default_service_name("deploy-agent")` prints
78    /// `deploy_agent`'s INFO lines). Until 2026-10-29 an application's INFO
79    /// lines (where it listens, which database it opened) were hidden unless
80    /// `RUST_LOG` named its crate.
81    ///
82    /// Under `OTEL_SDK_DISABLED=true` nothing is exported (`layer()` adds
83    /// nothing), but the printing layer is still installed: the variable
84    /// turns off the OpenTelemetry SDK, and says nothing about a process's own
85    /// warnings and errors. Until 2026-10-31 it installed nothing, so a process
86    /// told to export nothing also lost every warning, its own and the SDK's
87    /// (audit C-07). It never replaces a global subscriber that was already
88    /// set; [`try_install_subscriber`](Self::try_install_subscriber) says
89    /// whether it installed one. A process with its own subscriber adds
90    /// `layer()` to it instead.
91    pub fn install_subscriber(&self) {
92        let _installed = self.try_install_subscriber();
93    }
94
95    /// [`install_subscriber`](Self::install_subscriber), saying whether it
96    /// installed the subscriber: `false` when a global subscriber was already
97    /// set. Until 0.16.0 `install_subscriber` returned this, which every
98    /// caller but the tests ignored.
99    #[must_use]
100    pub fn try_install_subscriber(&self) -> bool {
101        use tracing_subscriber::layer::SubscriberExt as _;
102        use tracing_subscriber::util::SubscriberInitExt as _;
103        let rust_log = std::env::var("RUST_LOG").ok();
104        let (filter, not_understood) = diagnostics::filter(rust_log.as_deref());
105        // `RUST_LOG`, when set, says everything printed.
106        let app = rust_log
107            .as_deref()
108            .is_none_or(|v| v.trim().is_empty())
109            .then(|| self.app_target.clone())
110            .flatten();
111        let installed = tracing_subscriber::registry()
112            .with(self.layer())
113            .with(diagnostics::layer(
114                filter,
115                self.logs_on_console,
116                app,
117                self.console_format,
118            ))
119            .try_init()
120            .is_ok();
121        if installed {
122            if self.startup_summary {
123                tracing::info!("{}", self.describe());
124            }
125            for notice in not_understood.iter().chain(&self.notices) {
126                tracing::warn!("{notice}");
127            }
128        }
129        installed
130    }
131}