Skip to main content

dynamo_runtime/
logging.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Dynamo Distributed Logging Module.
5//!
6//! - Configuration loaded from:
7//!   1. Environment variables (highest priority).
8//!   2. Optional TOML file pointed to by the `DYN_LOGGING_CONFIG_PATH` environment variable.
9//!   3. `/opt/dynamo/etc/logging.toml`.
10//!
11//! Logging can take two console forms: `READABLE` or `JSONL`. Select one with
12//! `DYN_LOGGING_CONSOLE_FORMAT=readable|jsonl`; the default is `READABLE`.
13//! `DYN_LOGGING_JSONL=1` remains a legacy fallback when the new setting is unset or blank.
14//! Console presentation is independent of OpenTelemetry export.
15//!
16//! To use local timezone for logging timestamps, set the `DYN_LOG_USE_LOCAL_TZ` environment variable to `1`.
17//!
18//! Filters can be configured using the `DYN_LOG` environment variable or by setting the `filters`
19//! key in the TOML configuration file. Filters are comma-separated key-value pairs where the key
20//! is the crate or module name and the value is the log level. The default log level is `info`.
21//!
22//! Example:
23//! ```toml
24//! log_level = "error"
25//!
26//! [log_filters]
27//! "test_logging" = "info"
28//! "test_logging::api" = "trace"
29//! ```
30
31use std::collections::{BTreeMap, HashMap};
32use std::sync::{Once, OnceLock};
33
34use figment::{
35    Figment,
36    providers::{Format, Serialized, Toml},
37};
38use serde::{Deserialize, Serialize};
39use tracing::level_filters::LevelFilter;
40use tracing::{Event, Subscriber};
41use tracing_subscriber::EnvFilter;
42use tracing_subscriber::filter::Targets;
43use tracing_subscriber::fmt::time::FormatTime;
44use tracing_subscriber::fmt::time::LocalTime;
45use tracing_subscriber::fmt::time::SystemTime;
46use tracing_subscriber::fmt::time::UtcTime;
47use tracing_subscriber::fmt::{FmtContext, FormatFields};
48use tracing_subscriber::fmt::{FormattedFields, format::Writer};
49use tracing_subscriber::prelude::*;
50use tracing_subscriber::registry::LookupSpan;
51use tracing_subscriber::{filter::Directive, fmt};
52
53use crate::config::{
54    ConsoleLogFormat, console_log_format, disable_ansi_logging, env_is_truthy,
55    legacy_jsonl_logging_enabled, span_events_enabled,
56};
57use async_nats::{HeaderMap, HeaderValue};
58use axum::extract::FromRequestParts;
59use axum::http;
60use axum::http::Request;
61use axum::http::request::Parts;
62use serde_json::Value;
63use std::convert::Infallible;
64use std::time::Instant;
65use tower_http::trace::{DefaultMakeSpan, TraceLayer};
66use tracing::Id;
67use tracing::Span;
68use tracing::field::Field;
69use tracing::span;
70use tracing_subscriber::Layer;
71use tracing_subscriber::Registry;
72use tracing_subscriber::field::Visit;
73use tracing_subscriber::fmt::format::FmtSpan;
74use tracing_subscriber::layer::Context;
75use tracing_subscriber::layer::Filter;
76use tracing_subscriber::registry::SpanData;
77use uuid::Uuid;
78
79use opentelemetry::propagation::{Extractor, Injector, TextMapPropagator};
80use opentelemetry::trace::{Span as OtelSpan, TraceContextExt};
81use opentelemetry::{global, trace::Tracer};
82use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
83use opentelemetry_otlp::{WithExportConfig, WithTonicConfig};
84
85use opentelemetry::trace::TracerProvider as _;
86use opentelemetry::{Key, KeyValue};
87use opentelemetry_sdk::Resource;
88use opentelemetry_sdk::logs::SdkLoggerProvider;
89use opentelemetry_sdk::trace::Sampler;
90use opentelemetry_sdk::trace::SdkTracerProvider;
91use tracing::error;
92use tracing_subscriber::layer::SubscriberExt;
93// use tracing_subscriber::Registry;
94
95use std::time::Duration;
96use tracing::{info, instrument};
97use tracing_opentelemetry::OpenTelemetrySpanExt;
98use tracing_subscriber::util::SubscriberInitExt;
99
100use crate::config::environment_names::logging as env_logging;
101use crate::telemetry::{LIFECYCLE_TARGET, lifecycle_tracing_enabled};
102
103/// Default log level
104const DEFAULT_FILTER_LEVEL: &str = "info";
105
106/// Default OTLP endpoint
107const DEFAULT_OTLP_ENDPOINT: &str = "http://localhost:4317";
108
109/// Default OTLP HTTP endpoint
110const DEFAULT_OTLP_HTTP_ENDPOINT: &str = "http://localhost:4318";
111
112/// Default service name
113const DEFAULT_OTEL_SERVICE_NAME: &str = "dynamo";
114
115/// Once instance to ensure the logger is only initialized once
116static INIT: Once = Once::new();
117
118#[derive(Serialize, Deserialize, Debug)]
119struct LoggingConfig {
120    log_level: String,
121    log_filters: HashMap<String, String>,
122}
123impl Default for LoggingConfig {
124    fn default() -> Self {
125        LoggingConfig {
126            log_level: DEFAULT_FILTER_LEVEL.to_string(),
127            log_filters: HashMap::from([
128                ("h2".to_string(), "error".to_string()),
129                ("tower".to_string(), "error".to_string()),
130                ("hyper_util".to_string(), "error".to_string()),
131                ("neli".to_string(), "error".to_string()),
132                ("async_nats".to_string(), "error".to_string()),
133                ("rustls".to_string(), "error".to_string()),
134                ("tokenizers".to_string(), "error".to_string()),
135                ("axum".to_string(), "error".to_string()),
136                ("tonic".to_string(), "error".to_string()),
137                ("hf_hub".to_string(), "error".to_string()),
138                ("opentelemetry".to_string(), "error".to_string()),
139                ("opentelemetry-otlp".to_string(), "error".to_string()),
140                ("opentelemetry_sdk".to_string(), "error".to_string()),
141            ]),
142        }
143    }
144}
145
146/// Check if OTLP trace exporting is enabled (accepts: "1", "true", "on", "yes" - case insensitive)
147fn otlp_exporter_enabled() -> bool {
148    env_is_truthy(env_logging::otlp::OTEL_EXPORT_ENABLED)
149}
150
151/// Get the service name from environment or use default
152pub(crate) fn get_service_name() -> String {
153    std::env::var(env_logging::otlp::OTEL_SERVICE_NAME)
154        .unwrap_or_else(|_| DEFAULT_OTEL_SERVICE_NAME.to_string())
155}
156
157#[derive(Clone, Copy, Debug, Eq, PartialEq)]
158pub(crate) enum OtlpProtocol {
159    Grpc,
160    HttpProtobuf,
161}
162
163impl OtlpProtocol {
164    pub(crate) fn as_str(self) -> &'static str {
165        match self {
166            Self::Grpc => "grpc",
167            Self::HttpProtobuf => "http/protobuf",
168        }
169    }
170}
171
172fn parse_otlp_protocol_for_env(value: Option<&str>, env_name: &str) -> OtlpProtocol {
173    match value.map(str::trim).filter(|value| !value.is_empty()) {
174        None => OtlpProtocol::Grpc,
175        Some(value) if value.eq_ignore_ascii_case("grpc") => OtlpProtocol::Grpc,
176        Some(value) if value.eq_ignore_ascii_case("http/protobuf") => OtlpProtocol::HttpProtobuf,
177        Some(value) => {
178            eprintln!(
179                "WARNING: unsupported {} '{}'; falling back to grpc",
180                env_name, value
181            );
182            OtlpProtocol::Grpc
183        }
184    }
185}
186
187fn parse_otlp_protocol(value: Option<&str>) -> OtlpProtocol {
188    parse_otlp_protocol_for_env(value, env_logging::otlp::OTEL_EXPORTER_OTLP_PROTOCOL)
189}
190
191pub(crate) fn otlp_protocol_from_env() -> OtlpProtocol {
192    parse_otlp_protocol(
193        std::env::var(env_logging::otlp::OTEL_EXPORTER_OTLP_PROTOCOL)
194            .ok()
195            .as_deref(),
196    )
197}
198
199pub(crate) fn resolve_signal_otlp_protocol(
200    generic_protocol: OtlpProtocol,
201    signal_protocol: Option<&str>,
202    signal_protocol_env: &str,
203) -> OtlpProtocol {
204    match signal_protocol
205        .map(str::trim)
206        .filter(|value| !value.is_empty())
207    {
208        Some(value) => parse_otlp_protocol_for_env(Some(value), signal_protocol_env),
209        None => generic_protocol,
210    }
211}
212
213fn append_otlp_http_path(endpoint: &str, path: &str) -> String {
214    let endpoint = endpoint.trim_end_matches('/');
215    format!("{endpoint}{path}")
216}
217
218pub(crate) fn resolve_otlp_endpoint(
219    protocol: OtlpProtocol,
220    signal_endpoint: Option<String>,
221    generic_endpoint: Option<String>,
222    http_path: &str,
223) -> String {
224    if let Some(endpoint) = signal_endpoint.filter(|value| !value.trim().is_empty()) {
225        return endpoint;
226    }
227
228    match protocol {
229        OtlpProtocol::Grpc => generic_endpoint
230            .filter(|value| !value.trim().is_empty())
231            .unwrap_or_else(|| DEFAULT_OTLP_ENDPOINT.to_string()),
232        OtlpProtocol::HttpProtobuf => append_otlp_http_path(
233            generic_endpoint
234                .filter(|value| !value.trim().is_empty())
235                .as_deref()
236                .unwrap_or(DEFAULT_OTLP_HTTP_ENDPOINT),
237            http_path,
238        ),
239    }
240}
241
242fn parse_trace_sample_ratio(value: Option<&str>) -> Option<f64> {
243    let raw = value?;
244    match raw.parse::<f64>() {
245        Ok(value) if value.is_finite() && (0.0..=1.0).contains(&value) => Some(value),
246        _ => {
247            eprintln!(
248                "WARNING: invalid OTEL_TRACES_SAMPLE_RATIO '{}'; expected a number between 0.0 and 1.0, keeping default sampler",
249                raw
250            );
251            None
252        }
253    }
254}
255
256fn trace_sample_ratio_from_env() -> Option<f64> {
257    parse_trace_sample_ratio(
258        std::env::var(env_logging::otlp::OTEL_TRACES_SAMPLE_RATIO)
259            .ok()
260            .as_deref(),
261    )
262}
263
264pub(crate) fn otel_runtime_handle() -> std::io::Result<tokio::runtime::Handle> {
265    // Keep our own long-lived runtime for the exporter. Using the ambient one
266    // (Handle::try_current) pins the exporter to whatever runtime is live at init,
267    // since INIT (Once) runs setup once. If that's a #[tokio::test] runtime, export
268    // silently dies when it drops.
269    static OTEL_RUNTIME: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
270    if let Some(rt) = OTEL_RUNTIME.get() {
271        return Ok(rt.handle().clone());
272    }
273
274    let rt = tokio::runtime::Builder::new_multi_thread()
275        .worker_threads(1)
276        .thread_name("dynamo-otel-export")
277        .enable_all()
278        .build()?;
279    Ok(OTEL_RUNTIME.get_or_init(|| rt).handle().clone())
280}
281
282/// gRPC metadata carrying the configured OTLP headers.
283///
284/// `opentelemetry-otlp` reads `OTEL_EXPORTER_OTLP_HEADERS` only on its HTTP
285/// path ("as of now, this is only supported for HTTP requests"), and Dynamo
286/// defaults to gRPC -- so without this, an authenticated collector rejects
287/// every span and log while the variable looks configured. Signal-specific
288/// headers replace the generic set rather than merging, per the exporter spec.
289fn otlp_metadata_for(signal_env: &str) -> tonic::metadata::MetadataMap {
290    let mut metadata = tonic::metadata::MetadataMap::new();
291    let raw = std::env::var(signal_env)
292        .or_else(|_| std::env::var(env_logging::otlp::OTEL_EXPORTER_OTLP_HEADERS))
293        .unwrap_or_default();
294
295    for (key, value) in crate::metrics::otlp_export::parse_key_value_list(&raw) {
296        match (
297            tonic::metadata::MetadataKey::from_bytes(key.as_bytes()),
298            tonic::metadata::MetadataValue::try_from(&value),
299        ) {
300            (Ok(key), Ok(value)) => {
301                metadata.insert(key, value);
302            }
303            _ => tracing::warn!(header = %key, "skipping unusable OTLP header"),
304        }
305    }
306    metadata
307}
308
309fn build_span_exporter(
310    protocol: OtlpProtocol,
311    endpoint: &str,
312) -> Result<opentelemetry_otlp::SpanExporter, opentelemetry_otlp::ExporterBuildError> {
313    match protocol {
314        OtlpProtocol::Grpc => opentelemetry_otlp::SpanExporter::builder()
315            .with_tonic()
316            .with_endpoint(endpoint)
317            .with_metadata(otlp_metadata_for(
318                env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_HEADERS,
319            ))
320            .build(),
321        OtlpProtocol::HttpProtobuf => opentelemetry_otlp::SpanExporter::builder()
322            .with_http()
323            .with_endpoint(endpoint)
324            .build(),
325    }
326}
327
328fn build_log_exporter(
329    protocol: OtlpProtocol,
330    endpoint: &str,
331) -> Result<opentelemetry_otlp::LogExporter, opentelemetry_otlp::ExporterBuildError> {
332    match protocol {
333        OtlpProtocol::Grpc => opentelemetry_otlp::LogExporter::builder()
334            .with_tonic()
335            .with_endpoint(endpoint)
336            .with_metadata(otlp_metadata_for(
337                env_logging::otlp::OTEL_EXPORTER_OTLP_LOGS_HEADERS,
338            ))
339            .build(),
340        OtlpProtocol::HttpProtobuf => opentelemetry_otlp::LogExporter::builder()
341            .with_http()
342            .with_endpoint(endpoint)
343            .build(),
344    }
345}
346
347fn span_events_for_logging() -> FmtSpan {
348    if span_events_enabled() {
349        FmtSpan::CLOSE
350    } else {
351        FmtSpan::NONE
352    }
353}
354
355fn log_otel_init_status(
356    service_name: &str,
357    endpoint_opt: Option<(OtlpProtocol, String)>,
358    console_format: ConsoleLogFormat,
359) {
360    if let Some((protocol, endpoint)) = endpoint_opt {
361        tracing::info!(
362            endpoint = %endpoint,
363            protocol = %protocol.as_str(),
364            service = %service_name,
365            console_format = console_format.as_str(),
366            "OpenTelemetry OTLP export enabled (traces and logs)"
367        );
368    } else {
369        tracing::info!(
370            service = %service_name,
371            console_format = console_format.as_str(),
372            "OpenTelemetry OTLP export disabled, traces local only"
373        );
374    }
375}
376
377/// Validate a given trace ID according to W3C Trace Context specifications.
378/// A valid trace ID is a 32-character hexadecimal string (lowercase).
379pub fn is_valid_trace_id(trace_id: &str) -> bool {
380    trace_id.len() == 32 && trace_id.chars().all(|c| c.is_ascii_hexdigit())
381}
382
383/// Validate a given span ID according to W3C Trace Context specifications.
384/// A valid span ID is a 16-character hexadecimal string (lowercase).
385pub fn is_valid_span_id(span_id: &str) -> bool {
386    span_id.len() == 16 && span_id.chars().all(|c| c.is_ascii_hexdigit())
387}
388
389pub struct DistributedTraceIdLayer;
390
391#[derive(Debug, Clone, Serialize, Deserialize)]
392pub struct DistributedTraceContext {
393    pub trace_id: String,
394    pub span_id: String,
395    #[serde(
396        default = "default_trace_flags",
397        skip_serializing_if = "is_default_trace_flags"
398    )]
399    pub trace_flags: String,
400    #[serde(skip_serializing_if = "Option::is_none")]
401    pub parent_id: Option<String>,
402    #[serde(skip_serializing_if = "Option::is_none")]
403    pub tracestate: Option<String>,
404    #[serde(skip)]
405    start: Option<Instant>,
406    #[serde(skip)]
407    end: Option<Instant>,
408    #[serde(skip_serializing_if = "Option::is_none")]
409    pub x_request_id: Option<String>,
410    #[serde(skip_serializing_if = "Option::is_none")]
411    pub request_id: Option<String>,
412}
413
414/// Pending context data collected in on_new_span, to be finalized in on_enter
415#[derive(Debug, Clone)]
416struct PendingDistributedTraceContext {
417    trace_id: Option<String>,
418    span_id: Option<String>,
419    parent_id: Option<String>,
420    trace_flags: Option<String>,
421    tracestate: Option<String>,
422    x_request_id: Option<String>,
423    request_id: Option<String>,
424}
425
426/// Macro to emit a tracing event at a dynamic level with a custom target.
427macro_rules! emit_at_level {
428    ($level:expr, target: $target:expr, $($arg:tt)*) => {
429        // tracing::event! requires a compile-time constant level, so we must match
430        // on the runtime level and use a literal Level constant in each arm.
431        // See: https://github.com/tokio-rs/tracing/issues/2730
432        match $level {
433            &tracing::Level::ERROR => tracing::event!(target: $target, tracing::Level::ERROR, $($arg)*),
434            &tracing::Level::WARN => tracing::event!(target: $target, tracing::Level::WARN, $($arg)*),
435            &tracing::Level::INFO => tracing::event!(target: $target, tracing::Level::INFO, $($arg)*),
436            &tracing::Level::DEBUG => tracing::event!(target: $target, tracing::Level::DEBUG, $($arg)*),
437            &tracing::Level::TRACE => tracing::event!(target: $target, tracing::Level::TRACE, $($arg)*),
438        }
439    };
440}
441
442impl DistributedTraceContext {
443    /// Create a traceparent string from the context
444    pub fn create_traceparent(&self) -> String {
445        format!(
446            "00-{}-{}-{}",
447            self.trace_id,
448            self.span_id,
449            normalize_trace_flags(&self.trace_flags)
450        )
451    }
452}
453
454fn default_trace_flags() -> String {
455    "01".to_string()
456}
457
458fn is_default_trace_flags(trace_flags: &str) -> bool {
459    trace_flags == "01"
460}
461
462fn is_valid_trace_flags(trace_flags: &str) -> bool {
463    trace_flags.len() == 2 && trace_flags.chars().all(|c| c.is_ascii_hexdigit())
464}
465
466fn normalize_trace_flags(trace_flags: &str) -> String {
467    if is_valid_trace_flags(trace_flags) {
468        trace_flags.to_ascii_lowercase()
469    } else {
470        default_trace_flags()
471    }
472}
473
474fn current_otel_trace_flags() -> Option<String> {
475    let context = Span::current().context();
476    let span = context.span();
477    let span_context = span.span_context();
478    if !span_context.is_valid() {
479        return None;
480    }
481
482    Some(
483        if span_context.trace_flags().is_sampled() {
484            "01"
485        } else {
486            "00"
487        }
488        .to_string(),
489    )
490}
491
492/// Parse a traceparent string into its components
493pub fn parse_traceparent(traceparent: &str) -> (Option<String>, Option<String>, Option<String>) {
494    let (trace_parent, _) = extract_trace_parent(&TraceparentHeader(traceparent));
495    (
496        trace_parent.trace_id,
497        trace_parent.parent_id,
498        trace_parent.trace_flags,
499    )
500}
501
502#[derive(Debug, Clone, Default)]
503pub struct TraceParent {
504    pub trace_id: Option<String>,
505    pub parent_id: Option<String>,
506    pub trace_flags: Option<String>,
507    pub tracestate: Option<String>,
508    pub x_request_id: Option<String>,
509    pub request_id: Option<String>,
510}
511
512pub trait GenericHeaders {
513    fn get(&self, key: &str) -> Option<&str>;
514}
515
516struct TraceparentHeader<'a>(&'a str);
517
518impl GenericHeaders for TraceparentHeader<'_> {
519    fn get(&self, key: &str) -> Option<&str> {
520        (key == "traceparent").then_some(self.0)
521    }
522}
523
524impl GenericHeaders for async_nats::HeaderMap {
525    fn get(&self, key: &str) -> Option<&str> {
526        async_nats::HeaderMap::get(self, key).map(|value| value.as_str())
527    }
528}
529
530impl GenericHeaders for http::HeaderMap {
531    fn get(&self, key: &str) -> Option<&str> {
532        http::HeaderMap::get(self, key).and_then(|value| value.to_str().ok())
533    }
534}
535
536impl GenericHeaders for std::collections::HashMap<String, String> {
537    fn get(&self, key: &str) -> Option<&str> {
538        std::collections::HashMap::get(self, key).map(String::as_str)
539    }
540}
541
542struct GenericHeaderExtractor<'a, H>(&'a H);
543
544impl<H: GenericHeaders> Extractor for GenericHeaderExtractor<'_, H> {
545    fn get(&self, key: &str) -> Option<&str> {
546        self.0.get(key)
547    }
548
549    fn keys(&self) -> Vec<&str> {
550        ["traceparent", "tracestate"]
551            .into_iter()
552            .filter(|key| self.0.get(key).is_some())
553            .collect()
554    }
555}
556
557fn extract_trace_parent<H: GenericHeaders>(
558    headers: &H,
559) -> (TraceParent, Option<opentelemetry::Context>) {
560    let valid_widths = headers.get("traceparent").is_some_and(|header| {
561        let mut fields = header.trim().split('-');
562        let version_field = fields.next();
563        matches!(
564            (version_field, fields.next(), fields.next(), fields.next()),
565            (Some(version), Some(trace_id), Some(span_id), Some(flags))
566                if version.len() == 2
567                    && trace_id.len() == 32
568                    && span_id.len() == 16
569                    && flags.len() == 2
570        ) && (version_field != Some("00") || fields.next().is_none())
571    });
572    let context = if valid_widths {
573        TRACE_PROPAGATOR.extract_with_context(
574            &opentelemetry::Context::new(),
575            &GenericHeaderExtractor(headers),
576        )
577    } else {
578        opentelemetry::Context::new()
579    };
580    let span = context.span();
581    let span_context = span.span_context();
582    let (trace_id, parent_id, trace_flags, context) = if span_context.is_valid() {
583        (
584            Some(span_context.trace_id().to_string()),
585            Some(span_context.span_id().to_string()),
586            Some(format!("{:02x}", span_context.trace_flags().to_u8())),
587            Some(context),
588        )
589    } else {
590        (None, None, None, None)
591    };
592
593    // Transport hop only: workers read the frontend's forwarded `request-id`.
594    // HTTP ingress spans ignore it so a client cannot choose the internal request id.
595    let request_id = headers
596        .get("request-id")
597        .or_else(|| headers.get("x-dynamo-request-id"))
598        .filter(|id| uuid::Uuid::parse_str(id).is_ok())
599        .map(str::to_string);
600
601    (
602        TraceParent {
603            trace_id,
604            parent_id,
605            trace_flags,
606            tracestate: headers.get("tracestate").map(str::to_string),
607            x_request_id: headers.get("x-request-id").map(str::to_string),
608            request_id,
609        },
610        context,
611    )
612}
613
614impl TraceParent {
615    pub fn from_headers<H: GenericHeaders>(headers: &H) -> TraceParent {
616        extract_trace_parent(headers).0
617    }
618}
619
620/// Create a span for inference request endpoints (completions, chat, embeddings, etc.).
621///
622/// Uses `target: "request_span"` which is always allowed through the DYN_LOG filter
623/// (via `request_span=trace` directive in `filters()`). This ensures request context
624/// (request_id, model, trace_id) is always available on log events.
625pub fn make_inference_request_span<B>(req: &Request<B>) -> Span {
626    let method = req.method();
627    let uri = req.uri();
628    let version = format!("{:?}", req.version());
629    let (trace_parent, otel_context) = extract_trace_parent(req.headers());
630
631    // Always server-minted and the single source of truth; client `request-id` headers are
632    // ignored. Client correlation travels separately as `x_request_id`.
633    let request_id = Uuid::new_v4().to_string();
634
635    let span = tracing::info_span!(
636            target: "request_span",
637        "http-request",
638        method = %method,
639        uri = %uri,
640        version = %version,
641        trace_id = trace_parent.trace_id,
642        parent_id = trace_parent.parent_id,
643        trace_flags = trace_parent.trace_flags,
644        x_request_id = trace_parent.x_request_id,
645        request_id = %request_id,
646        model = tracing::field::Empty,
647        "request.outcome" = tracing::field::Empty,
648        input_tokens = tracing::field::Empty,
649        output_tokens = tracing::field::Empty,
650        image_count = tracing::field::Empty,
651        video_count = tracing::field::Empty,
652        audio_count = tracing::field::Empty,
653        ttft_ms = tracing::field::Empty,
654        avg_itl_ms = tracing::field::Empty,
655        prefill_worker_id = tracing::field::Empty,
656        decode_worker_id = tracing::field::Empty,
657    );
658
659    if let Some(context) = otel_context {
660        let _ = span.set_parent(context);
661    }
662
663    span
664}
665
666/// Create a span for system endpoints (health, metrics, models, engine, loras, etc.).
667///
668/// Same structure as `make_inference_request_span` but uses `target: "system_span"`
669/// which follows normal DYN_LOG filtering (debug level by default). The inference
670/// span target `request_span` is always-on via a `request_span=trace` directive;
671/// system spans are not, keeping high-frequency polling endpoints quiet.
672pub fn make_system_request_span<B>(req: &Request<B>) -> Span {
673    let method = req.method();
674    let uri = req.uri();
675    let version = format!("{:?}", req.version());
676    let (trace_parent, otel_context) = extract_trace_parent(req.headers());
677
678    let request_id = Uuid::new_v4().to_string();
679
680    let span = tracing::debug_span!(
681        target: "system_span",
682        "http-request",
683        method = %method,
684        uri = %uri,
685        version = %version,
686        trace_id = trace_parent.trace_id,
687        parent_id = trace_parent.parent_id,
688        trace_flags = trace_parent.trace_flags,
689        x_request_id = trace_parent.x_request_id,
690        request_id = %request_id,
691        model = tracing::field::Empty,
692        input_tokens = tracing::field::Empty,
693        output_tokens = tracing::field::Empty,
694        image_count = tracing::field::Empty,
695        video_count = tracing::field::Empty,
696        audio_count = tracing::field::Empty,
697        ttft_ms = tracing::field::Empty,
698        avg_itl_ms = tracing::field::Empty,
699        prefill_worker_id = tracing::field::Empty,
700        decode_worker_id = tracing::field::Empty,
701    );
702
703    if let Some(context) = otel_context {
704        let _ = span.set_parent(context);
705    }
706
707    span
708}
709
710/// Create a handle_payload span from NATS headers with component context
711pub fn make_handle_payload_span(
712    headers: &async_nats::HeaderMap,
713    component: &str,
714    endpoint: &str,
715    namespace: &str,
716    instance_id: u64,
717) -> Span {
718    let (trace_parent, otel_context) = extract_trace_parent(headers);
719    let trace_id = trace_parent.trace_id.as_ref();
720    let parent_span_id = trace_parent.parent_id.as_ref();
721
722    if let (Some(trace_id), Some(parent_id)) = (trace_id, parent_span_id) {
723        let span = tracing::info_span!(
724            target: "request_span",
725            "handle_payload",
726            otel.kind = "server",
727            trace_id = trace_id.as_str(),
728            parent_id = parent_id.as_str(),
729            trace_flags = trace_parent.trace_flags,
730            x_request_id = trace_parent.x_request_id,
731            request_id = trace_parent.request_id,
732            tracestate = trace_parent.tracestate,
733            component = component,
734            endpoint = endpoint,
735            namespace = namespace,
736            instance_id = instance_id,
737        );
738
739        if let Some(context) = otel_context {
740            let _ = span.set_parent(context);
741        }
742        span
743    } else {
744        tracing::info_span!(
745            target: "request_span",
746            "handle_payload",
747            otel.kind = "server",
748            trace_flags = trace_parent.trace_flags,
749            x_request_id = trace_parent.x_request_id,
750            request_id = trace_parent.request_id,
751            tracestate = trace_parent.tracestate,
752            component = component,
753            endpoint = endpoint,
754            namespace = namespace,
755            instance_id = instance_id,
756        )
757    }
758}
759
760/// Create a handle_payload span from TCP/HashMap headers with component context
761pub fn make_handle_payload_span_from_tcp_headers(
762    headers: &std::collections::HashMap<String, String>,
763    component: &str,
764    endpoint: &str,
765    namespace: &str,
766    instance_id: u64,
767) -> Span {
768    let (trace_parent, otel_context) = extract_trace_parent(headers);
769
770    if let (Some(trace_id), Some(parent_id)) = (
771        trace_parent.trace_id.as_ref(),
772        trace_parent.parent_id.as_ref(),
773    ) {
774        let span = tracing::info_span!(
775            target: "request_span",
776            "handle_payload",
777            otel.kind = "server",
778            trace_id = trace_id.as_str(),
779            parent_id = parent_id.as_str(),
780            trace_flags = trace_parent.trace_flags,
781            x_request_id = trace_parent.x_request_id,
782            request_id = trace_parent.request_id,
783            tracestate = trace_parent.tracestate,
784            component = component,
785            endpoint = endpoint,
786            namespace = namespace,
787            instance_id = instance_id,
788        );
789
790        if let Some(context) = otel_context {
791            let _ = span.set_parent(context);
792        }
793        span
794    } else {
795        tracing::info_span!(
796            target: "request_span",
797            "handle_payload",
798            otel.kind = "server",
799            trace_flags = trace_parent.trace_flags,
800            x_request_id = trace_parent.x_request_id,
801            request_id = trace_parent.request_id,
802            tracestate = trace_parent.tracestate,
803            component = component,
804            endpoint = endpoint,
805            namespace = namespace,
806            instance_id = instance_id,
807        )
808    }
809}
810
811/// Extract OpenTelemetry trace context from NATS headers for distributed tracing
812pub fn extract_otel_context_from_nats_headers(
813    headers: &async_nats::HeaderMap,
814) -> (
815    Option<opentelemetry::Context>,
816    Option<String>,
817    Option<String>,
818) {
819    let (trace_parent, context) = extract_trace_parent(headers);
820    (context, trace_parent.trace_id, trace_parent.parent_id)
821}
822
823/// Inject OpenTelemetry trace context into NATS headers using W3C Trace Context propagation
824pub fn inject_otel_context_into_nats_headers(
825    headers: &mut async_nats::HeaderMap,
826    context: Option<opentelemetry::Context>,
827) {
828    let otel_context = context.unwrap_or_else(|| Span::current().context());
829
830    struct NatsHeaderInjector<'a>(&'a mut async_nats::HeaderMap);
831
832    impl<'a> Injector for NatsHeaderInjector<'a> {
833        fn set(&mut self, key: &str, value: String) {
834            self.0.insert(key, value);
835        }
836    }
837
838    let mut injector = NatsHeaderInjector(headers);
839    TRACE_PROPAGATOR.inject_context(&otel_context, &mut injector);
840}
841
842/// Inject trace context from current span into NATS headers
843pub fn inject_current_trace_into_nats_headers(headers: &mut async_nats::HeaderMap) {
844    inject_otel_context_into_nats_headers(headers, None);
845}
846
847// Inject trace headers into a generic HashMap for HTTP/TCP transports
848pub fn inject_trace_headers_into_map(headers: &mut std::collections::HashMap<String, String>) {
849    if let Some(trace_context) = get_distributed_tracing_context() {
850        // Inject W3C traceparent header
851        headers.insert(
852            "traceparent".to_string(),
853            trace_context.create_traceparent(),
854        );
855
856        // Inject optional tracestate
857        if let Some(tracestate) = trace_context.tracestate {
858            headers.insert("tracestate".to_string(), tracestate);
859        }
860
861        // Inject custom request IDs
862        if let Some(x_request_id) = trace_context.x_request_id {
863            headers.insert("x-request-id".to_string(), x_request_id);
864        }
865        if let Some(request_id) = trace_context.request_id {
866            headers.insert("request-id".to_string(), request_id);
867        }
868    }
869}
870
871pub fn otel_parent_context_from_distributed(
872    ctx: &DistributedTraceContext,
873) -> Option<opentelemetry::Context> {
874    let mut headers = async_nats::HeaderMap::new();
875    headers.insert("traceparent", ctx.create_traceparent());
876
877    if let Some(ref tracestate) = ctx.tracestate {
878        headers.insert("tracestate", tracestate.as_str());
879    }
880
881    let (otel_context, _trace_id, _parent_span_id) =
882        extract_otel_context_from_nats_headers(&headers);
883    otel_context
884}
885
886/// Create a client_request span linked to the parent trace context
887pub fn make_client_request_span(
888    operation: &str,
889    request_id: &str,
890    trace_context: Option<&DistributedTraceContext>,
891    instance_id: Option<&str>,
892) -> Span {
893    if let Some(ctx) = trace_context {
894        let otel_context = otel_parent_context_from_distributed(ctx);
895
896        let span = if let Some(inst_id) = instance_id {
897            tracing::info_span!(
898                "client_request",
899                operation = operation,
900                request_id = request_id,
901                instance_id = inst_id,
902                trace_id = ctx.trace_id.as_str(),
903                parent_id = ctx.span_id.as_str(),
904                trace_flags = ctx.trace_flags.as_str(),
905                x_request_id = ctx.x_request_id.as_deref(),
906            )
907        } else {
908            tracing::info_span!(
909                "client_request",
910                operation = operation,
911                request_id = request_id,
912                trace_id = ctx.trace_id.as_str(),
913                parent_id = ctx.span_id.as_str(),
914                trace_flags = ctx.trace_flags.as_str(),
915                x_request_id = ctx.x_request_id.as_deref(),
916            )
917        };
918
919        if let Some(context) = otel_context {
920            let _ = span.set_parent(context);
921        }
922
923        span
924    } else if let Some(inst_id) = instance_id {
925        tracing::info_span!(
926            "client_request",
927            operation = operation,
928            request_id = request_id,
929            instance_id = inst_id,
930        )
931    } else {
932        tracing::info_span!(
933            "client_request",
934            operation = operation,
935            request_id = request_id,
936        )
937    }
938}
939
940#[derive(Debug, Default)]
941pub struct FieldVisitor {
942    pub fields: HashMap<String, String>,
943}
944
945impl Visit for FieldVisitor {
946    fn record_str(&mut self, field: &Field, value: &str) {
947        self.fields
948            .insert(field.name().to_string(), value.to_string());
949    }
950
951    fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
952        self.fields
953            .insert(field.name().to_string(), format!("{:?}", value).to_string());
954    }
955}
956
957impl<S> Layer<S> for DistributedTraceIdLayer
958where
959    S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
960{
961    // Capture close span time
962    // Currently not used but added for future use in timing
963    fn on_close(&self, id: Id, ctx: Context<'_, S>) {
964        if let Some(span) = ctx.span(&id) {
965            let mut extensions = span.extensions_mut();
966            if let Some(distributed_tracing_context) =
967                extensions.get_mut::<DistributedTraceContext>()
968            {
969                distributed_tracing_context.end = Some(Instant::now());
970            }
971        }
972    }
973
974    // Collects span attributes and metadata in on_new_span
975    // Final initialization deferred to on_enter when OtelData is available
976    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
977        if let Some(span) = ctx.span(id) {
978            let mut trace_id: Option<String> = None;
979            let mut parent_id: Option<String> = None;
980            let mut span_id: Option<String> = None;
981            let mut trace_flags: Option<String> = None;
982            let mut x_request_id: Option<String> = None;
983            let mut request_id: Option<String> = None;
984            let mut tracestate: Option<String> = None;
985            let mut visitor = FieldVisitor::default();
986            attrs.record(&mut visitor);
987
988            // Extract trace_id from span attributes
989            if let Some(trace_id_input) = visitor.fields.get("trace_id") {
990                if !is_valid_trace_id(trace_id_input) {
991                    tracing::trace!("trace id  '{trace_id_input}' is not valid! Ignoring.");
992                } else {
993                    trace_id = Some(trace_id_input.to_string());
994                }
995            }
996
997            // Extract span_id from span attributes
998            if let Some(span_id_input) = visitor.fields.get("span_id") {
999                if !is_valid_span_id(span_id_input) {
1000                    tracing::trace!("span id  '{span_id_input}' is not valid! Ignoring.");
1001                } else {
1002                    span_id = Some(span_id_input.to_string());
1003                }
1004            }
1005
1006            // Extract parent_id from span attributes
1007            if let Some(parent_id_input) = visitor.fields.get("parent_id") {
1008                if !is_valid_span_id(parent_id_input) {
1009                    tracing::trace!("parent id  '{parent_id_input}' is not valid! Ignoring.");
1010                } else {
1011                    parent_id = Some(parent_id_input.to_string());
1012                }
1013            }
1014
1015            if let Some(trace_flags_input) = visitor.fields.get("trace_flags") {
1016                if !is_valid_trace_flags(trace_flags_input) {
1017                    tracing::trace!("trace flags '{trace_flags_input}' are not valid! Ignoring.");
1018                } else {
1019                    trace_flags = Some(trace_flags_input.to_ascii_lowercase());
1020                }
1021            }
1022
1023            // Extract tracestate
1024            if let Some(tracestate_input) = visitor.fields.get("tracestate") {
1025                tracestate = Some(tracestate_input.to_string());
1026            }
1027
1028            // Extract x_request_id
1029            if let Some(x_request_id_input) = visitor.fields.get("x_request_id") {
1030                x_request_id = Some(x_request_id_input.to_string());
1031            }
1032
1033            // Extract request_id (with backward compat for x_dynamo_request_id)
1034            if let Some(request_id_input) = visitor.fields.get("request_id") {
1035                request_id = Some(request_id_input.to_string());
1036            } else if let Some(x_request_id_input) = visitor.fields.get("x_dynamo_request_id") {
1037                request_id = Some(x_request_id_input.to_string());
1038            }
1039
1040            // Inherit trace context from parent span if available
1041            if parent_id.is_none()
1042                && let Some(parent_span_id) = ctx.current_span().id()
1043                && let Some(parent_span) = ctx.span(parent_span_id)
1044            {
1045                let parent_ext = parent_span.extensions();
1046                if let Some(parent_tracing_context) = parent_ext.get::<DistributedTraceContext>() {
1047                    trace_id = Some(parent_tracing_context.trace_id.clone());
1048                    parent_id = Some(parent_tracing_context.span_id.clone());
1049                    if trace_flags.is_none() {
1050                        trace_flags = Some(parent_tracing_context.trace_flags.clone());
1051                    }
1052                    tracestate = parent_tracing_context.tracestate.clone();
1053                    if x_request_id.is_none() {
1054                        x_request_id = parent_tracing_context.x_request_id.clone();
1055                    }
1056                    if request_id.is_none() {
1057                        request_id = parent_tracing_context.request_id.clone();
1058                    }
1059                }
1060            }
1061
1062            // Validate consistency
1063            if (parent_id.is_some() || span_id.is_some()) && trace_id.is_none() {
1064                tracing::error!("parent id or span id are set but trace id is not set!");
1065                // Clear inconsistent IDs to maintain trace integrity
1066                parent_id = None;
1067                span_id = None;
1068            }
1069
1070            // Store pending context - will be finalized in on_enter
1071            let mut extensions = span.extensions_mut();
1072            extensions.insert(PendingDistributedTraceContext {
1073                trace_id,
1074                span_id,
1075                parent_id,
1076                trace_flags,
1077                tracestate,
1078                x_request_id,
1079                request_id,
1080            });
1081        }
1082    }
1083
1084    // Finalizes the DistributedTraceContext when span is entered
1085    // At this point, OtelData should have valid trace_id and span_id
1086    fn on_enter(&self, id: &Id, ctx: Context<'_, S>) {
1087        if let Some(span) = ctx.span(id) {
1088            // Check if already initialized (e.g., span re-entered)
1089            {
1090                let extensions = span.extensions();
1091                if extensions.get::<DistributedTraceContext>().is_some() {
1092                    return;
1093                }
1094            }
1095
1096            // Get the pending context and extract OtelData IDs
1097            let mut extensions = span.extensions_mut();
1098            let pending = match extensions.remove::<PendingDistributedTraceContext>() {
1099                Some(p) => p,
1100                None => {
1101                    // This shouldn't happen - on_new_span should have created it
1102                    tracing::error!("PendingDistributedTraceContext not found in on_enter");
1103                    return;
1104                }
1105            };
1106
1107            let mut trace_id = pending.trace_id;
1108            let mut span_id = pending.span_id;
1109            let parent_id = pending.parent_id;
1110            let mut trace_flags = pending.trace_flags;
1111            let tracestate = pending.tracestate;
1112            let x_request_id = pending.x_request_id;
1113            let request_id = pending.request_id;
1114
1115            // Try to extract from OtelData if not already set
1116            // Need to drop extensions_mut to get immutable borrow for OtelData
1117            drop(extensions);
1118
1119            if trace_id.is_none() || span_id.is_none() {
1120                let extensions = span.extensions();
1121                if let Some(otel_data) = extensions.get::<tracing_opentelemetry::OtelData>() {
1122                    // Extract trace_id from OTEL data if not already set
1123                    if trace_id.is_none()
1124                        && let Some(otel_trace_id) = otel_data.trace_id()
1125                    {
1126                        let trace_id_str = format!("{}", otel_trace_id);
1127                        if is_valid_trace_id(&trace_id_str) {
1128                            trace_id = Some(trace_id_str);
1129                        }
1130                    }
1131
1132                    // Extract span_id from OTEL data if not already set
1133                    if span_id.is_none()
1134                        && let Some(otel_span_id) = otel_data.span_id()
1135                    {
1136                        let span_id_str = format!("{}", otel_span_id);
1137                        if is_valid_span_id(&span_id_str) {
1138                            span_id = Some(span_id_str);
1139                        }
1140                    }
1141                }
1142            }
1143
1144            if trace_flags.is_none() {
1145                trace_flags = current_otel_trace_flags();
1146            }
1147
1148            // Panic if we still don't have required IDs
1149            if trace_id.is_none() {
1150                panic!(
1151                    "trace_id is not set in on_enter - OtelData may not be properly initialized"
1152                );
1153            }
1154
1155            if span_id.is_none() {
1156                panic!("span_id is not set in on_enter - OtelData may not be properly initialized");
1157            }
1158
1159            let span_level = span.metadata().level();
1160            let mut extensions = span.extensions_mut();
1161            extensions.insert(DistributedTraceContext {
1162                trace_id: trace_id.expect("Trace ID must be set"),
1163                span_id: span_id.expect("Span ID must be set"),
1164                trace_flags: trace_flags.unwrap_or_else(default_trace_flags),
1165                parent_id,
1166                tracestate,
1167                start: Some(Instant::now()),
1168                end: None,
1169                x_request_id,
1170                request_id,
1171            });
1172
1173            drop(extensions);
1174
1175            // Emit SPAN_FIRST_ENTRY event. This only runs if the span passed the layer's filter
1176            // (on_enter is not called for filtered-out spans), so no additional check needed.
1177            if span_events_enabled() {
1178                emit_at_level!(span_level, target: "span_event", message = "SPAN_FIRST_ENTRY");
1179            }
1180        }
1181    }
1182}
1183
1184// Enables functions to retreive their current
1185// context for adding to distributed headers
1186pub fn get_distributed_tracing_context() -> Option<DistributedTraceContext> {
1187    Span::current()
1188        .with_subscriber(|(id, subscriber)| {
1189            subscriber
1190                .downcast_ref::<Registry>()
1191                .and_then(|registry| registry.span_data(id))
1192                .and_then(|span_data| {
1193                    let extensions = span_data.extensions();
1194                    extensions.get::<DistributedTraceContext>().cloned()
1195                })
1196        })
1197        .flatten()
1198        .map(|mut context| {
1199            // Propagate this node's live OTel sampling decision (W3C: `sampled`
1200            // reflects the immediate caller, not the original client), so a
1201            // non-parent sampler overrides the inbound flag downstream.
1202            if let Some(trace_flags) = current_otel_trace_flags() {
1203                context.trace_flags = trace_flags;
1204            }
1205            context
1206        })
1207}
1208
1209/// Initialize logging (idempotent). Safe to call with or without a running
1210/// Tokio runtime — OTLP exporters fall back to a persistent background runtime.
1211pub fn init() {
1212    INIT.call_once(|| {
1213        if let Err(e) = setup_logging() {
1214            eprintln!("Failed to initialize logging: {}", e);
1215            std::process::exit(1);
1216        }
1217    });
1218}
1219
1220#[cfg(feature = "tokio-console")]
1221fn setup_logging() -> Result<(), Box<dyn std::error::Error>> {
1222    let tokio_console_layer = console_subscriber::ConsoleLayer::builder()
1223        .with_default_env()
1224        .server_addr(([0, 0, 0, 0], console_subscriber::Server::DEFAULT_PORT))
1225        .spawn();
1226    let tokio_console_target = tracing_subscriber::filter::Targets::new()
1227        .with_default(LevelFilter::ERROR)
1228        .with_target("runtime", LevelFilter::TRACE)
1229        .with_target("tokio", LevelFilter::TRACE);
1230    let l = console_layer(console_log_format(), FmtSpan::NONE, filters(load_config()));
1231    tracing_subscriber::registry()
1232        .with(l)
1233        .with(tokio_console_layer.with_filter(tokio_console_target))
1234        .init();
1235    Ok(())
1236}
1237
1238#[cfg(not(feature = "tokio-console"))]
1239fn setup_logging() -> Result<(), Box<dyn std::error::Error>> {
1240    let fmt_filter_layer = filters(load_config());
1241    let trace_filter_layer = filters(load_config());
1242    let otel_filter_layer = otel_filters(load_config(), lifecycle_tracing_enabled());
1243    let otel_logs_filter_layer = filters(load_config());
1244    let console_format = console_log_format();
1245    let legacy_jsonl_enabled = legacy_jsonl_logging_enabled();
1246    let otlp_enabled = otlp_exporter_enabled();
1247    // Keep the legacy JSONL switch as a trace-context signal even when the new
1248    // setting overrides console presentation. Older deployments rely on it for
1249    // downstream trace propagation without OTLP export.
1250    let trace_context_enabled =
1251        otlp_enabled || legacy_jsonl_enabled || console_format == ConsoleLogFormat::Jsonl;
1252    let span_events = if trace_context_enabled {
1253        span_events_for_logging()
1254    } else {
1255        FmtSpan::NONE
1256    };
1257
1258    if trace_context_enabled {
1259        let service_name = get_service_name();
1260        let sample_ratio = trace_sample_ratio_from_env();
1261
1262        // Build tracer and logger providers - with or without OTLP export
1263        let (tracer_provider, logger_provider_opt, endpoint_opt) = if otlp_enabled {
1264            // Building the OTLP exporters spawns a background flush task, so it needs a
1265            // live, persistent reactor
1266            let otel_handle = otel_runtime_handle()?;
1267            let _otel_reactor_guard = otel_handle.enter();
1268            let protocol = otlp_protocol_from_env();
1269            let traces_protocol = resolve_signal_otlp_protocol(
1270                protocol,
1271                std::env::var(env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_PROTOCOL)
1272                    .ok()
1273                    .as_deref(),
1274                env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_PROTOCOL,
1275            );
1276            let logs_protocol = resolve_signal_otlp_protocol(
1277                protocol,
1278                std::env::var(env_logging::otlp::OTEL_EXPORTER_OTLP_LOGS_PROTOCOL)
1279                    .ok()
1280                    .as_deref(),
1281                env_logging::otlp::OTEL_EXPORTER_OTLP_LOGS_PROTOCOL,
1282            );
1283            let generic_endpoint =
1284                std::env::var(env_logging::otlp::OTEL_EXPORTER_OTLP_ENDPOINT).ok();
1285            let traces_endpoint_env =
1286                std::env::var(env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_ENDPOINT).ok();
1287            let logs_endpoint_env =
1288                std::env::var(env_logging::otlp::OTEL_EXPORTER_OTLP_LOGS_ENDPOINT).ok();
1289            let traces_endpoint = resolve_otlp_endpoint(
1290                traces_protocol,
1291                traces_endpoint_env,
1292                generic_endpoint.clone(),
1293                "/v1/traces",
1294            );
1295            let logs_endpoint = resolve_otlp_endpoint(
1296                logs_protocol,
1297                logs_endpoint_env,
1298                generic_endpoint,
1299                "/v1/logs",
1300            );
1301
1302            let resource = opentelemetry_sdk::Resource::builder_empty()
1303                .with_service_name(service_name.clone())
1304                .build();
1305
1306            let span_exporter = build_span_exporter(traces_protocol, &traces_endpoint)?;
1307
1308            let mut tracer_provider_builder =
1309                opentelemetry_sdk::trace::SdkTracerProvider::builder()
1310                    .with_batch_exporter(span_exporter)
1311                    .with_resource(resource.clone());
1312            if let Some(sample_ratio) = sample_ratio {
1313                tracer_provider_builder = tracer_provider_builder.with_sampler(
1314                    Sampler::ParentBased(Box::new(Sampler::TraceIdRatioBased(sample_ratio))),
1315                );
1316            }
1317            let tracer_provider = tracer_provider_builder.build();
1318
1319            let log_exporter = build_log_exporter(logs_protocol, &logs_endpoint)?;
1320
1321            let logger_provider = SdkLoggerProvider::builder()
1322                .with_batch_exporter(log_exporter)
1323                .with_resource(resource)
1324                .build();
1325
1326            (
1327                tracer_provider,
1328                Some(logger_provider),
1329                Some((traces_protocol, traces_endpoint)),
1330            )
1331        } else {
1332            // No export - traces generated locally only (for logging/trace IDs)
1333            let mut provider_builder = opentelemetry_sdk::trace::SdkTracerProvider::builder()
1334                .with_resource(
1335                    opentelemetry_sdk::Resource::builder_empty()
1336                        .with_service_name(service_name.clone())
1337                        .build(),
1338                );
1339            if let Some(sample_ratio) = sample_ratio {
1340                provider_builder = provider_builder.with_sampler(Sampler::ParentBased(Box::new(
1341                    Sampler::TraceIdRatioBased(sample_ratio),
1342                )));
1343            }
1344            let provider = provider_builder.build();
1345
1346            (provider, None, None)
1347        };
1348
1349        // Register the provider globally so direct OTel API users
1350        // (`opentelemetry::global::tracer(...)`) hit the same exporter as
1351        // the tracing-opentelemetry bridge below. Without this, ad-hoc
1352        // OTel spans created via `global::tracer()` go to the default
1353        // no-op provider and are silently dropped.
1354        // Cheap — `SdkTracerProvider` is Arc-shared internally.
1355        opentelemetry::global::set_tracer_provider(tracer_provider.clone());
1356
1357        let tracer = tracer_provider.tracer(service_name.to_string());
1358        // Filter outside the `Option`: a bare `None` layer registers interest in every
1359        // callsite, so each disabled `debug!`/`trace!` would run every per-layer filter
1360        // on every call instead of being skipped at its callsite.
1361        let otel_logs_layer = logger_provider_opt
1362            .as_ref()
1363            .map(OpenTelemetryTracingBridge::new)
1364            .with_filter(otel_logs_filter_layer);
1365
1366        let l = console_layer(console_format, span_events, fmt_filter_layer);
1367        tracing_subscriber::registry()
1368            .with(
1369                tracing_opentelemetry::layer()
1370                    .with_tracer(tracer)
1371                    .with_filter(otel_filter_layer),
1372            )
1373            .with(otel_logs_layer)
1374            .with(DistributedTraceIdLayer.with_filter(trace_filter_layer))
1375            .with(l)
1376            .init();
1377
1378        log_otel_init_status(&service_name, endpoint_opt, console_format);
1379    } else {
1380        let l = console_layer(console_format, span_events, fmt_filter_layer);
1381
1382        tracing_subscriber::registry().with(l).init();
1383    }
1384
1385    Ok(())
1386}
1387
1388/// Console (stderr) fmt layer whose event format is selected by
1389/// `DYN_LOGGING_CONSOLE_FORMAT`, independent of the OTel export state.
1390fn console_layer<S>(
1391    format: ConsoleLogFormat,
1392    span_events: FmtSpan,
1393    filter_layer: LoggingFilter,
1394) -> impl Layer<S>
1395where
1396    S: Subscriber + for<'a> LookupSpan<'a> + 'static,
1397{
1398    fmt::layer()
1399        .with_ansi(format == ConsoleLogFormat::Readable && !disable_ansi_logging())
1400        .with_span_events(span_events)
1401        .event_format(ConsoleEventFormatter::new(format))
1402        .with_writer(std::io::stderr)
1403        .with_filter(filter_layer)
1404}
1405
1406type ReadableEventFormatter = tracing_subscriber::fmt::format::Format<
1407    tracing_subscriber::fmt::format::Compact,
1408    TimeFormatter,
1409>;
1410
1411enum ConsoleEventFormatter {
1412    Readable(ReadableEventFormatter),
1413    Jsonl(CustomJsonFormatter),
1414}
1415
1416impl ConsoleEventFormatter {
1417    fn new(format: ConsoleLogFormat) -> Self {
1418        match format {
1419            ConsoleLogFormat::Readable => {
1420                Self::Readable(fmt::format().compact().with_timer(TimeFormatter::new()))
1421            }
1422            ConsoleLogFormat::Jsonl => Self::Jsonl(CustomJsonFormatter::new()),
1423        }
1424    }
1425}
1426
1427impl<S, N> tracing_subscriber::fmt::FormatEvent<S, N> for ConsoleEventFormatter
1428where
1429    S: Subscriber + for<'a> LookupSpan<'a>,
1430    N: for<'a> FormatFields<'a> + 'static,
1431{
1432    fn format_event(
1433        &self,
1434        ctx: &FmtContext<'_, S, N>,
1435        writer: Writer<'_>,
1436        event: &Event<'_>,
1437    ) -> std::fmt::Result {
1438        match self {
1439            Self::Readable(formatter) => {
1440                tracing_subscriber::fmt::FormatEvent::format_event(formatter, ctx, writer, event)
1441            }
1442            Self::Jsonl(formatter) => {
1443                tracing_subscriber::fmt::FormatEvent::format_event(formatter, ctx, writer, event)
1444            }
1445        }
1446    }
1447}
1448
1449#[allow(clippy::large_enum_variant)] // Constructed once during logging initialization.
1450enum LoggingFilter {
1451    Targets(Targets),
1452    Env(EnvFilter),
1453}
1454
1455impl<S> Filter<S> for LoggingFilter {
1456    #[inline]
1457    fn enabled(&self, meta: &tracing::Metadata<'_>, cx: &Context<'_, S>) -> bool {
1458        match self {
1459            Self::Targets(filter) => <Targets as Filter<S>>::enabled(filter, meta, cx),
1460            Self::Env(filter) => <EnvFilter as Filter<S>>::enabled(filter, meta, cx),
1461        }
1462    }
1463
1464    #[inline]
1465    fn callsite_enabled(
1466        &self,
1467        meta: &'static tracing::Metadata<'static>,
1468    ) -> tracing::subscriber::Interest {
1469        match self {
1470            Self::Targets(filter) => <Targets as Filter<S>>::callsite_enabled(filter, meta),
1471            Self::Env(filter) => <EnvFilter as Filter<S>>::callsite_enabled(filter, meta),
1472        }
1473    }
1474
1475    #[inline]
1476    fn event_enabled(&self, event: &Event<'_>, cx: &Context<'_, S>) -> bool {
1477        match self {
1478            Self::Targets(filter) => <Targets as Filter<S>>::event_enabled(filter, event, cx),
1479            Self::Env(filter) => <EnvFilter as Filter<S>>::event_enabled(filter, event, cx),
1480        }
1481    }
1482
1483    #[inline]
1484    fn max_level_hint(&self) -> Option<LevelFilter> {
1485        match self {
1486            Self::Targets(filter) => <Targets as Filter<S>>::max_level_hint(filter),
1487            Self::Env(filter) => <EnvFilter as Filter<S>>::max_level_hint(filter),
1488        }
1489    }
1490
1491    #[inline]
1492    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &Id, cx: Context<'_, S>) {
1493        if let Self::Env(filter) = self {
1494            <EnvFilter as Filter<S>>::on_new_span(filter, attrs, id, cx);
1495        }
1496    }
1497
1498    #[inline]
1499    fn on_record(&self, id: &Id, values: &span::Record<'_>, cx: Context<'_, S>) {
1500        if let Self::Env(filter) = self {
1501            <EnvFilter as Filter<S>>::on_record(filter, id, values, cx);
1502        }
1503    }
1504
1505    #[inline]
1506    fn on_enter(&self, id: &Id, cx: Context<'_, S>) {
1507        if let Self::Env(filter) = self {
1508            <EnvFilter as Filter<S>>::on_enter(filter, id, cx);
1509        }
1510    }
1511
1512    #[inline]
1513    fn on_exit(&self, id: &Id, cx: Context<'_, S>) {
1514        if let Self::Env(filter) = self {
1515            <EnvFilter as Filter<S>>::on_exit(filter, id, cx);
1516        }
1517    }
1518
1519    #[inline]
1520    fn on_close(&self, id: Id, cx: Context<'_, S>) {
1521        if let Self::Env(filter) = self {
1522            <EnvFilter as Filter<S>>::on_close(filter, id, cx);
1523        }
1524    }
1525}
1526
1527#[derive(Debug)]
1528enum TargetsFilterFallback {
1529    Dynamic,
1530    Other,
1531}
1532
1533/// Lifecycle spans bypass `DYN_LOG` only in the OTel layer. The console
1534/// formatter keeps its normal filter, so enabling lifecycle tracing does not
1535/// increase stderr logging volume.
1536fn otel_filters(mut config: LoggingConfig, lifecycle_enabled: bool) -> LoggingFilter {
1537    if lifecycle_enabled {
1538        config
1539            .log_filters
1540            .insert(LIFECYCLE_TARGET.to_string(), "info".to_string());
1541    }
1542    filters(config)
1543}
1544
1545fn filters(config: LoggingConfig) -> LoggingFilter {
1546    let targets = match std::env::var(env_logging::DYN_LOG) {
1547        Ok(value) => targets_filter(&config, Some(&value)),
1548        Err(std::env::VarError::NotPresent) => targets_filter(&config, None),
1549        Err(std::env::VarError::NotUnicode(_)) => Err(TargetsFilterFallback::Other),
1550    };
1551
1552    match targets {
1553        Ok(filter) => LoggingFilter::Targets(filter),
1554        Err(TargetsFilterFallback::Dynamic) => {
1555            // Logging has not been initialized yet, so write directly to stderr
1556            // rather than through tracing. This must remain visible even when the
1557            // configured dynamic filter excludes WARN-level events.
1558            eprintln!(
1559                "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\
1560                 !!! WARNING: DYNAMIC LOG FILTERS FORCE THE EnvFilter FALLBACK !!!\n\
1561                 !!! This disables Dynamo's lock-free logging fast path and can severely\n\
1562                 !!! degrade request performance, especially for streaming responses.\n\
1563                 !!! Remove span/field selectors ([...]) from DYN_LOG or log_filters to\n\
1564                 !!! re-enable the fast target/level filter.\n\
1565                 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
1566            );
1567            LoggingFilter::Env(env_filter(&config))
1568        }
1569        Err(TargetsFilterFallback::Other) => LoggingFilter::Env(env_filter(&config)),
1570    }
1571}
1572
1573/// Use the lock-free target/level filter when `DYN_LOG` contains no dynamic
1574/// span or field directives. `EnvFilter` tracks dynamic span matches behind an
1575/// `RwLock`, and its span lifecycle callbacks acquire that lock even when the
1576/// configured directives are all static.
1577fn targets_filter(
1578    config: &LoggingConfig,
1579    dyn_log: Option<&str>,
1580) -> Result<Targets, TargetsFilterFallback> {
1581    // `EnvFilter::parse_lossy` ignores zero-length comma-separated segments,
1582    // but leaves all other text untouched. In particular, do not trim here:
1583    // whitespace may make the directive dynamic or invalid.
1584    let dyn_directives = dyn_log
1585        .into_iter()
1586        .flat_map(|value| value.split(',').filter(|directive| !directive.is_empty()));
1587
1588    let mut directives = Vec::new();
1589    for directive in dyn_directives {
1590        // Parsing as `Targets` is also the feature test for whether the
1591        // configured directive requires EnvFilter's dynamic span matching.
1592        targets_compatible(directive)?;
1593        directives.push(directive.to_string());
1594    }
1595
1596    // EnvFilter uses the configured default only when DYN_LOG is absent or
1597    // contains no directives. A target-only DYN_LOG must leave other targets
1598    // disabled rather than inheriting the configured default level.
1599    if directives.is_empty() {
1600        directives.push(config.log_level.clone());
1601    }
1602
1603    for (module, level) in &config.log_filters {
1604        let directive = format!("{module}={level}");
1605        match targets_compatible(&directive) {
1606            Ok(()) => directives.push(directive),
1607            Err(fallback) => match directive.parse::<Directive>() {
1608                // Valid span or field directives require EnvFilter's dynamic
1609                // matching, so do not silently drop a configured filter.
1610                Ok(_) => return Err(fallback),
1611                // Preserve the pre-fast-path warn-and-ignore behavior for
1612                // directives that neither parser accepts.
1613                Err(e) => {
1614                    eprintln!("Failed parsing filter '{level}' for module '{module}': {e}");
1615                }
1616            },
1617        }
1618    }
1619
1620    if span_events_enabled() {
1621        directives.push("span_event=trace".to_string());
1622    }
1623
1624    directives.push("request_span=trace".to_string());
1625    directives
1626        .join(",")
1627        .parse::<Targets>()
1628        .map_err(|_| TargetsFilterFallback::Other)
1629}
1630
1631/// An opening `[` begins EnvFilter's span or field selector grammar. Targets
1632/// accepts some bracketed forms as literal targets or static field filters, but
1633/// routing every bracketed directive through EnvFilter keeps the configuration
1634/// language consistent. Curly braces alone remain ordinary target characters.
1635fn targets_compatible(directive: &str) -> Result<(), TargetsFilterFallback> {
1636    if directive.contains('[') {
1637        Err(TargetsFilterFallback::Dynamic)
1638    } else if directive.parse::<Targets>().is_ok() {
1639        Ok(())
1640    } else {
1641        Err(TargetsFilterFallback::Other)
1642    }
1643}
1644
1645fn env_filter(config: &LoggingConfig) -> EnvFilter {
1646    let mut filter_layer = EnvFilter::builder()
1647        .with_default_directive(config.log_level.parse().unwrap())
1648        .with_env_var(env_logging::DYN_LOG)
1649        .from_env_lossy();
1650
1651    for (module, level) in &config.log_filters {
1652        match format!("{module}={level}").parse::<Directive>() {
1653            Ok(d) => {
1654                filter_layer = filter_layer.add_directive(d);
1655            }
1656            Err(e) => {
1657                eprintln!("Failed parsing filter '{level}' for module '{module}': {e}");
1658            }
1659        }
1660    }
1661
1662    // When span events are enabled, allow "span_event" target at all levels
1663    // This ensures SPAN_FIRST_ENTRY events pass the filter when emitted from on_enter
1664    if span_events_enabled() {
1665        filter_layer = filter_layer.add_directive("span_event=trace".parse().unwrap());
1666    }
1667
1668    // Always allow infrastructure request spans regardless of DYN_LOG level.
1669    // This ensures request context (request_id, model, trace_id) is always
1670    // available on log events, even when DYN_LOG=error or DYN_LOG=warn.
1671    // Can be overridden via DYN_LOG=request_span=<level> if needed.
1672    filter_layer = filter_layer.add_directive("request_span=trace".parse().unwrap());
1673
1674    filter_layer
1675}
1676
1677/// Log a message with file and line info
1678/// Used by Python wrapper
1679pub fn log_message(level: &str, message: &str, module: &str, file: &str, line: u32) {
1680    let level = match level {
1681        "debug" => log::Level::Debug,
1682        "info" => log::Level::Info,
1683        "warn" => log::Level::Warn,
1684        "error" => log::Level::Error,
1685        "warning" => log::Level::Warn,
1686        _ => log::Level::Info,
1687    };
1688    log::logger().log(
1689        &log::Record::builder()
1690            .args(format_args!("{}", message))
1691            .level(level)
1692            .target(module)
1693            .file(Some(file))
1694            .line(Some(line))
1695            .build(),
1696    );
1697}
1698
1699fn load_config() -> LoggingConfig {
1700    let config_path =
1701        std::env::var(env_logging::DYN_LOGGING_CONFIG_PATH).unwrap_or_else(|_| "".to_string());
1702    let figment = Figment::new()
1703        .merge(Serialized::defaults(LoggingConfig::default()))
1704        .merge(Toml::file("/opt/dynamo/etc/logging.toml"))
1705        .merge(Toml::file(config_path));
1706
1707    figment.extract().unwrap()
1708}
1709
1710#[derive(Serialize)]
1711struct JsonLog<'a> {
1712    time: String,
1713    level: String,
1714    #[serde(skip_serializing_if = "Option::is_none")]
1715    file: Option<&'a str>,
1716    #[serde(skip_serializing_if = "Option::is_none")]
1717    line: Option<u32>,
1718    target: String,
1719    message: serde_json::Value,
1720    #[serde(flatten)]
1721    fields: BTreeMap<String, serde_json::Value>,
1722}
1723
1724struct TimeFormatter {
1725    use_local_tz: bool,
1726}
1727
1728impl TimeFormatter {
1729    fn new() -> Self {
1730        Self {
1731            use_local_tz: crate::config::use_local_timezone(),
1732        }
1733    }
1734
1735    fn format_now(&self) -> String {
1736        if self.use_local_tz {
1737            chrono::Local::now()
1738                .format("%Y-%m-%dT%H:%M:%S%.6f%:z")
1739                .to_string()
1740        } else {
1741            chrono::Utc::now()
1742                .format("%Y-%m-%dT%H:%M:%S%.6fZ")
1743                .to_string()
1744        }
1745    }
1746}
1747
1748impl FormatTime for TimeFormatter {
1749    fn format_time(&self, w: &mut fmt::format::Writer<'_>) -> std::fmt::Result {
1750        write!(w, "{}", self.format_now())
1751    }
1752}
1753
1754struct CustomJsonFormatter {
1755    time_formatter: TimeFormatter,
1756}
1757
1758impl CustomJsonFormatter {
1759    fn new() -> Self {
1760        Self {
1761            time_formatter: TimeFormatter::new(),
1762        }
1763    }
1764}
1765
1766use once_cell::sync::Lazy;
1767use regex::Regex;
1768
1769/// Static W3C Trace Context propagator instance to avoid repeated allocations
1770static TRACE_PROPAGATOR: Lazy<opentelemetry_sdk::propagation::TraceContextPropagator> =
1771    Lazy::new(opentelemetry_sdk::propagation::TraceContextPropagator::new);
1772
1773fn parse_tracing_duration(s: &str) -> Option<u64> {
1774    static RE: Lazy<Regex> =
1775        Lazy::new(|| Regex::new(r#"^["']?\s*([0-9.]+)\s*(µs|us|ns|ms|s)\s*["']?$"#).unwrap());
1776    let captures = RE.captures(s)?;
1777    let value: f64 = captures[1].parse().ok()?;
1778    let unit = &captures[2];
1779    match unit {
1780        "ns" => Some((value / 1000.0) as u64),
1781        "µs" | "us" => Some(value as u64),
1782        "ms" => Some((value * 1000.0) as u64),
1783        "s" => Some((value * 1_000_000.0) as u64),
1784        _ => None,
1785    }
1786}
1787
1788impl<S, N> tracing_subscriber::fmt::FormatEvent<S, N> for CustomJsonFormatter
1789where
1790    S: Subscriber + for<'a> LookupSpan<'a>,
1791    N: for<'a> FormatFields<'a> + 'static,
1792{
1793    fn format_event(
1794        &self,
1795        ctx: &FmtContext<'_, S, N>,
1796        mut writer: Writer<'_>,
1797        event: &Event<'_>,
1798    ) -> std::fmt::Result {
1799        let mut visitor = JsonVisitor::default();
1800        let time = self.time_formatter.format_now();
1801        event.record(&mut visitor);
1802        let mut message = visitor
1803            .fields
1804            .remove("message")
1805            .unwrap_or(serde_json::Value::String("".to_string()));
1806
1807        let mut target_override: Option<String> = None;
1808
1809        let current_span = event
1810            .parent()
1811            .and_then(|id| ctx.span(id))
1812            .or_else(|| ctx.lookup_current());
1813        if let Some(span) = current_span {
1814            let ext = span.extensions();
1815            let data = ext.get::<FormattedFields<N>>().unwrap();
1816            let span_fields: Vec<(&str, &str)> = data
1817                .fields
1818                .split(' ')
1819                .filter_map(|entry| entry.split_once('='))
1820                .collect();
1821            for (name, value) in span_fields {
1822                visitor.fields.insert(
1823                    name.to_string(),
1824                    serde_json::Value::String(value.trim_matches('"').to_string()),
1825                );
1826            }
1827
1828            let busy_us = visitor
1829                .fields
1830                .remove("time.busy")
1831                .and_then(|v| parse_tracing_duration(&v.to_string()));
1832            let idle_us = visitor
1833                .fields
1834                .remove("time.idle")
1835                .and_then(|v| parse_tracing_duration(&v.to_string()));
1836
1837            if let (Some(busy_us), Some(idle_us)) = (busy_us, idle_us) {
1838                visitor.fields.insert(
1839                    "time.busy_us".to_string(),
1840                    serde_json::Value::Number(busy_us.into()),
1841                );
1842                visitor.fields.insert(
1843                    "time.idle_us".to_string(),
1844                    serde_json::Value::Number(idle_us.into()),
1845                );
1846                visitor.fields.insert(
1847                    "time.duration_us".to_string(),
1848                    serde_json::Value::Number((busy_us + idle_us).into()),
1849                );
1850            }
1851
1852            let is_span_created = message.as_str() == Some("SPAN_FIRST_ENTRY");
1853            let is_span_closed = message.as_str() == Some("close");
1854            if is_span_created || is_span_closed {
1855                target_override = Some(span.metadata().target().to_string());
1856                if is_span_closed {
1857                    message = serde_json::Value::String("SPAN_CLOSED".to_string());
1858                }
1859            }
1860
1861            visitor.fields.insert(
1862                "span_name".to_string(),
1863                serde_json::Value::String(span.name().to_string()),
1864            );
1865
1866            if let Some(tracing_context) = ext.get::<DistributedTraceContext>() {
1867                visitor.fields.insert(
1868                    "span_id".to_string(),
1869                    serde_json::Value::String(tracing_context.span_id.clone()),
1870                );
1871                visitor.fields.insert(
1872                    "trace_id".to_string(),
1873                    serde_json::Value::String(tracing_context.trace_id.clone()),
1874                );
1875                if let Some(parent_id) = tracing_context.parent_id.clone() {
1876                    visitor.fields.insert(
1877                        "parent_id".to_string(),
1878                        serde_json::Value::String(parent_id),
1879                    );
1880                } else {
1881                    visitor.fields.remove("parent_id");
1882                }
1883                if let Some(tracestate) = tracing_context.tracestate.clone() {
1884                    visitor.fields.insert(
1885                        "tracestate".to_string(),
1886                        serde_json::Value::String(tracestate),
1887                    );
1888                } else {
1889                    visitor.fields.remove("tracestate");
1890                }
1891                if let Some(x_request_id) = tracing_context.x_request_id.clone() {
1892                    visitor.fields.insert(
1893                        "x_request_id".to_string(),
1894                        serde_json::Value::String(x_request_id),
1895                    );
1896                } else {
1897                    visitor.fields.remove("x_request_id");
1898                }
1899
1900                if let Some(request_id) = tracing_context.request_id.clone() {
1901                    visitor.fields.insert(
1902                        "request_id".to_string(),
1903                        serde_json::Value::String(request_id),
1904                    );
1905                } else {
1906                    visitor.fields.remove("request_id");
1907                }
1908                // Remove old field name if present
1909                visitor.fields.remove("x_dynamo_request_id");
1910            } else {
1911                tracing::error!(
1912                    "Distributed Trace Context not found, falling back to internal ids"
1913                );
1914                visitor.fields.insert(
1915                    "span_id".to_string(),
1916                    serde_json::Value::String(span.id().into_u64().to_string()),
1917                );
1918                if let Some(parent) = span.parent() {
1919                    visitor.fields.insert(
1920                        "parent_id".to_string(),
1921                        serde_json::Value::String(parent.id().into_u64().to_string()),
1922                    );
1923                }
1924            }
1925        } else {
1926            let reserved_fields = [
1927                "trace_id",
1928                "span_id",
1929                "parent_id",
1930                "span_name",
1931                "tracestate",
1932            ];
1933            for reserved_field in reserved_fields {
1934                visitor.fields.remove(reserved_field);
1935            }
1936        }
1937        let metadata = event.metadata();
1938        let log = JsonLog {
1939            level: metadata.level().to_string(),
1940            time,
1941            file: metadata.file(),
1942            line: metadata.line(),
1943            target: target_override.unwrap_or_else(|| metadata.target().to_string()),
1944            message,
1945            fields: visitor.fields,
1946        };
1947        let json = serde_json::to_string(&log).unwrap();
1948        writeln!(writer, "{json}")
1949    }
1950}
1951
1952#[derive(Default)]
1953struct JsonVisitor {
1954    fields: BTreeMap<String, serde_json::Value>,
1955}
1956
1957impl tracing::field::Visit for JsonVisitor {
1958    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
1959        self.fields.insert(
1960            field.name().to_string(),
1961            serde_json::Value::String(format!("{value:?}")),
1962        );
1963    }
1964
1965    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
1966        if field.name() != "message" {
1967            match serde_json::from_str::<Value>(value) {
1968                Ok(json_val) => self.fields.insert(field.name().to_string(), json_val),
1969                Err(_) => self.fields.insert(field.name().to_string(), value.into()),
1970            };
1971        } else {
1972            self.fields.insert(field.name().to_string(), value.into());
1973        }
1974    }
1975
1976    fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
1977        self.fields
1978            .insert(field.name().to_string(), serde_json::Value::Bool(value));
1979    }
1980
1981    fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
1982        self.fields.insert(
1983            field.name().to_string(),
1984            serde_json::Value::Number(value.into()),
1985        );
1986    }
1987
1988    fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
1989        self.fields.insert(
1990            field.name().to_string(),
1991            serde_json::Value::Number(value.into()),
1992        );
1993    }
1994
1995    fn record_f64(&mut self, field: &tracing::field::Field, value: f64) {
1996        use serde_json::value::Number;
1997        self.fields.insert(
1998            field.name().to_string(),
1999            serde_json::Value::Number(Number::from_f64(value).unwrap_or(0.into())),
2000        );
2001    }
2002}
2003
2004#[cfg(test)]
2005pub mod tests {
2006    use super::*;
2007    use anyhow::{Result, anyhow};
2008    use chrono::{DateTime, Utc};
2009    use jsonschema::{Draft, JSONSchema};
2010    use serde_json::Value;
2011    use std::fs::File;
2012    use std::io::{BufRead, BufReader};
2013    use stdio_override::*;
2014    use tempfile::NamedTempFile;
2015
2016    #[test]
2017    fn unset_dyn_log_uses_configured_default() {
2018        let filter = targets_filter(&LoggingConfig::default(), None)
2019            .expect("an unset DYN_LOG should use Targets");
2020
2021        assert!(filter.would_enable("request_span", &tracing::Level::TRACE));
2022        assert!(filter.would_enable("unlisted_target", &tracing::Level::INFO));
2023        assert!(!filter.would_enable("unlisted_target", &tracing::Level::DEBUG));
2024        assert!(!filter.would_enable("tower", &tracing::Level::WARN));
2025    }
2026
2027    #[test]
2028    fn empty_dyn_log_uses_configured_default() {
2029        for dyn_log in ["", ",,"] {
2030            let filter = targets_filter(&LoggingConfig::default(), Some(dyn_log))
2031                .expect("an empty DYN_LOG should use Targets");
2032
2033            assert!(filter.would_enable("request_span", &tracing::Level::TRACE));
2034            assert!(filter.would_enable("unlisted_target", &tracing::Level::INFO));
2035            assert!(!filter.would_enable("unlisted_target", &tracing::Level::DEBUG));
2036            assert!(!filter.would_enable("tower", &tracing::Level::WARN));
2037        }
2038    }
2039
2040    #[test]
2041    fn target_only_dyn_log_does_not_use_configured_default() {
2042        let filter = targets_filter(
2043            &LoggingConfig::default(),
2044            Some("dynamo_runtime::logging=debug"),
2045        )
2046        .expect("target/level directives should use Targets");
2047
2048        assert!(filter.would_enable("request_span", &tracing::Level::TRACE));
2049        assert!(!filter.would_enable("unlisted_target", &tracing::Level::INFO));
2050        assert!(!filter.would_enable("unlisted_target", &tracing::Level::DEBUG));
2051        assert!(filter.would_enable("dynamo_runtime::logging::child", &tracing::Level::DEBUG));
2052        assert!(!filter.would_enable("tower", &tracing::Level::WARN));
2053    }
2054
2055    #[test]
2056    fn trailing_empty_dyn_log_segments_do_not_enable_trace() {
2057        let filter = targets_filter(
2058            &LoggingConfig::default(),
2059            Some("dynamo_runtime::logging=debug,"),
2060        )
2061        .expect("target/level directives should use Targets");
2062
2063        assert!(filter.would_enable("dynamo_runtime::logging", &tracing::Level::DEBUG));
2064        assert!(!filter.would_enable("unlisted_target", &tracing::Level::TRACE));
2065    }
2066
2067    #[test]
2068    fn dynamic_span_directives_fall_back_to_env_filter() {
2069        assert!(matches!(
2070            targets_filter(
2071                &LoggingConfig::default(),
2072                Some("dynamo_runtime[request{model=foo}]=debug"),
2073            ),
2074            Err(TargetsFilterFallback::Dynamic)
2075        ));
2076    }
2077
2078    #[test]
2079    fn span_selector_dyn_log_falls_back_to_env_filter() {
2080        assert!(matches!(
2081            targets_filter(
2082                &LoggingConfig::default(),
2083                Some("dynamo_runtime[request]=debug"),
2084            ),
2085            Err(TargetsFilterFallback::Dynamic)
2086        ));
2087    }
2088
2089    #[test]
2090    fn field_presence_dyn_log_falls_back_to_env_filter() {
2091        assert!(matches!(
2092            targets_filter(
2093                &LoggingConfig::default(),
2094                Some("dynamo_runtime[{request_id}]=debug"),
2095            ),
2096            Err(TargetsFilterFallback::Dynamic)
2097        ));
2098    }
2099
2100    #[test]
2101    fn dynamic_log_filters_fall_back_to_env_filter() {
2102        let config = LoggingConfig {
2103            log_level: DEFAULT_FILTER_LEVEL.to_string(),
2104            log_filters: HashMap::from([(
2105                "dynamo_runtime[request{model=foo}]".to_string(),
2106                "debug".to_string(),
2107            )]),
2108        };
2109
2110        assert!(matches!(
2111            targets_filter(&config, None),
2112            Err(TargetsFilterFallback::Dynamic)
2113        ));
2114    }
2115
2116    #[test]
2117    fn span_selector_log_filters_fall_back_to_env_filter() {
2118        let config = LoggingConfig {
2119            log_level: DEFAULT_FILTER_LEVEL.to_string(),
2120            log_filters: HashMap::from([(
2121                "dynamo_runtime[request]".to_string(),
2122                "debug".to_string(),
2123            )]),
2124        };
2125
2126        assert!(matches!(
2127            targets_filter(&config, None),
2128            Err(TargetsFilterFallback::Dynamic)
2129        ));
2130    }
2131
2132    #[test]
2133    fn field_presence_log_filters_fall_back_to_env_filter() {
2134        let config = LoggingConfig {
2135            log_level: DEFAULT_FILTER_LEVEL.to_string(),
2136            log_filters: HashMap::from([(
2137                "dynamo_runtime[{request_id}]".to_string(),
2138                "debug".to_string(),
2139            )]),
2140        };
2141
2142        assert!(matches!(
2143            targets_filter(&config, None),
2144            Err(TargetsFilterFallback::Dynamic)
2145        ));
2146    }
2147
2148    #[test]
2149    fn otlp_protocol_defaults_to_grpc() {
2150        assert_eq!(parse_otlp_protocol(None), OtlpProtocol::Grpc);
2151        assert_eq!(parse_otlp_protocol(Some("")), OtlpProtocol::Grpc);
2152        assert_eq!(parse_otlp_protocol(Some("grpc")), OtlpProtocol::Grpc);
2153        assert_eq!(
2154            parse_otlp_protocol(Some("http/protobuf")),
2155            OtlpProtocol::HttpProtobuf
2156        );
2157        assert_eq!(
2158            parse_otlp_protocol(Some("HTTP/PROTOBUF")),
2159            OtlpProtocol::HttpProtobuf
2160        );
2161        assert_eq!(parse_otlp_protocol(Some("bad")), OtlpProtocol::Grpc);
2162    }
2163
2164    #[test]
2165    fn otlp_signal_protocol_overrides_generic_protocol() {
2166        let generic_protocol = OtlpProtocol::Grpc;
2167        assert_eq!(
2168            resolve_signal_otlp_protocol(
2169                generic_protocol,
2170                Some("http/protobuf"),
2171                env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_PROTOCOL,
2172            ),
2173            OtlpProtocol::HttpProtobuf
2174        );
2175        assert_eq!(
2176            resolve_signal_otlp_protocol(
2177                generic_protocol,
2178                Some(""),
2179                env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_PROTOCOL,
2180            ),
2181            OtlpProtocol::Grpc
2182        );
2183        assert_eq!(
2184            resolve_signal_otlp_protocol(
2185                generic_protocol,
2186                None,
2187                env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_PROTOCOL,
2188            ),
2189            OtlpProtocol::Grpc
2190        );
2191    }
2192
2193    #[test]
2194    fn otlp_http_endpoint_appends_signal_paths_from_generic_endpoint() {
2195        assert_eq!(
2196            resolve_otlp_endpoint(
2197                OtlpProtocol::HttpProtobuf,
2198                None,
2199                Some("https://llm-observe.weizhipin.com".to_string()),
2200                "/v1/traces",
2201            ),
2202            "https://llm-observe.weizhipin.com/v1/traces"
2203        );
2204        assert_eq!(
2205            resolve_otlp_endpoint(
2206                OtlpProtocol::HttpProtobuf,
2207                None,
2208                Some("https://llm-observe.weizhipin.com/".to_string()),
2209                "/v1/logs",
2210            ),
2211            "https://llm-observe.weizhipin.com/v1/logs"
2212        );
2213        assert_eq!(
2214            resolve_otlp_endpoint(
2215                OtlpProtocol::HttpProtobuf,
2216                None,
2217                Some("https://llm-observe.weizhipin.com/v1/traces".to_string()),
2218                "/v1/traces",
2219            ),
2220            "https://llm-observe.weizhipin.com/v1/traces/v1/traces"
2221        );
2222    }
2223
2224    #[test]
2225    fn otlp_signal_endpoint_is_used_verbatim() {
2226        assert_eq!(
2227            resolve_otlp_endpoint(
2228                OtlpProtocol::HttpProtobuf,
2229                Some("https://collector.example/custom/traces".to_string()),
2230                Some("https://collector.example".to_string()),
2231                "/v1/traces",
2232            ),
2233            "https://collector.example/custom/traces"
2234        );
2235    }
2236
2237    #[test]
2238    fn otlp_grpc_endpoint_keeps_generic_endpoint_verbatim() {
2239        assert_eq!(
2240            resolve_otlp_endpoint(
2241                OtlpProtocol::Grpc,
2242                None,
2243                Some("http://otel-collector:4317".to_string()),
2244                "/v1/traces",
2245            ),
2246            "http://otel-collector:4317"
2247        );
2248    }
2249
2250    #[test]
2251    fn trace_sample_ratio_is_optional_and_bounded() {
2252        assert_eq!(parse_trace_sample_ratio(None), None);
2253        assert_eq!(parse_trace_sample_ratio(Some("0")), Some(0.0));
2254        assert_eq!(parse_trace_sample_ratio(Some("0.01")), Some(0.01));
2255        assert_eq!(parse_trace_sample_ratio(Some("1")), Some(1.0));
2256        assert_eq!(parse_trace_sample_ratio(Some("-0.1")), None);
2257        assert_eq!(parse_trace_sample_ratio(Some("1.1")), None);
2258        assert_eq!(parse_trace_sample_ratio(Some("nan")), None);
2259        assert_eq!(parse_trace_sample_ratio(Some("bad")), None);
2260    }
2261
2262    static LOG_LINE_SCHEMA: &str = r#"
2263    {
2264      "$schema": "http://json-schema.org/draft-07/schema#",
2265      "title": "Runtime Log Line",
2266      "type": "object",
2267      "required": [
2268        "file",
2269        "level",
2270        "line",
2271        "message",
2272        "target",
2273        "time"
2274      ],
2275      "properties": {
2276        "file":      { "type": "string" },
2277        "level":     { "type": "string", "enum": ["ERROR", "WARN", "INFO", "DEBUG", "TRACE"] },
2278        "line":      { "type": "integer" },
2279        "message":   { "type": "string" },
2280        "target":    { "type": "string" },
2281        "time":      { "type": "string", "format": "date-time" },
2282        "span_id":   { "type": "string", "pattern": "^[a-f0-9]{16}$" },
2283        "parent_id": { "type": "string", "pattern": "^[a-f0-9]{16}$" },
2284        "trace_id":  { "type": "string", "pattern": "^[a-f0-9]{32}$" },
2285        "span_name": { "type": "string" },
2286        "time.busy_us":     { "type": "integer" },
2287        "time.duration_us": { "type": "integer" },
2288        "time.idle_us":     { "type": "integer" },
2289        "tracestate": { "type": "string" }
2290      },
2291      "additionalProperties": true
2292    }
2293    "#;
2294
2295    #[tracing::instrument(skip_all)]
2296    async fn parent() {
2297        tracing::trace!(message = "parent!");
2298        if let Some(my_ctx) = get_distributed_tracing_context() {
2299            tracing::info!(my_trace_id = my_ctx.trace_id);
2300        }
2301        child().await;
2302    }
2303
2304    #[tracing::instrument(skip_all)]
2305    async fn child() {
2306        tracing::trace!(message = "child");
2307        if let Some(my_ctx) = get_distributed_tracing_context() {
2308            tracing::info!(my_trace_id = my_ctx.trace_id);
2309        }
2310        grandchild().await;
2311    }
2312
2313    #[tracing::instrument(skip_all)]
2314    async fn grandchild() {
2315        tracing::trace!(message = "grandchild");
2316        if let Some(my_ctx) = get_distributed_tracing_context() {
2317            tracing::info!(my_trace_id = my_ctx.trace_id);
2318        }
2319    }
2320
2321    pub fn load_log(file_name: &str) -> Result<Vec<serde_json::Value>> {
2322        let schema_json: Value =
2323            serde_json::from_str(LOG_LINE_SCHEMA).expect("schema parse failure");
2324        let compiled_schema = JSONSchema::options()
2325            .with_draft(Draft::Draft7)
2326            .compile(&schema_json)
2327            .expect("Invalid schema");
2328
2329        let f = File::open(file_name)?;
2330        let reader = BufReader::new(f);
2331        let mut result = Vec::new();
2332
2333        for (line_num, line) in reader.lines().enumerate() {
2334            let line = line?;
2335            let val: Value = serde_json::from_str(&line)
2336                .map_err(|e| anyhow!("Line {}: invalid JSON: {}", line_num + 1, e))?;
2337
2338            if let Err(errors) = compiled_schema.validate(&val) {
2339                let errs = errors.map(|e| e.to_string()).collect::<Vec<_>>().join("; ");
2340                return Err(anyhow!(
2341                    "Line {}: JSON Schema Validation errors: {}",
2342                    line_num + 1,
2343                    errs
2344                ));
2345            }
2346            println!("{}", val);
2347            result.push(val);
2348        }
2349        Ok(result)
2350    }
2351
2352    // Field validators (W3C Trace Context): each rule is tested directly here.
2353    // The parse_traceparent tests below only cover parsing/structure + wiring,
2354    // not the per-field rules.
2355
2356    #[test]
2357    fn is_valid_trace_id_requires_32_hex() {
2358        assert!(is_valid_trace_id(&"a".repeat(32)));
2359        assert!(is_valid_trace_id("0123456789abcdefABCDEF0123456789")); // case-insensitive
2360        assert!(!is_valid_trace_id(&"1".repeat(31))); // too short
2361        assert!(!is_valid_trace_id(&"1".repeat(33))); // too long
2362        assert!(!is_valid_trace_id(&format!("{}g", "1".repeat(31)))); // non-hex
2363        assert!(!is_valid_trace_id("")); // empty
2364    }
2365
2366    #[test]
2367    fn is_valid_span_id_requires_16_hex() {
2368        assert!(is_valid_span_id(&"2".repeat(16)));
2369        assert!(!is_valid_span_id(&"2".repeat(15))); // too short
2370        assert!(!is_valid_span_id(&"2".repeat(17))); // too long
2371        assert!(!is_valid_span_id(&format!("{}g", "2".repeat(15)))); // non-hex
2372        assert!(!is_valid_span_id("")); // empty
2373    }
2374
2375    #[test]
2376    fn is_valid_trace_flags_requires_2_hex() {
2377        assert!(is_valid_trace_flags("00"));
2378        assert!(is_valid_trace_flags("ff")); // any 2 hex digits are structurally valid
2379        assert!(is_valid_trace_flags("0A")); // case-insensitive
2380        assert!(!is_valid_trace_flags("0")); // too short
2381        assert!(!is_valid_trace_flags("000")); // too long
2382        assert!(!is_valid_trace_flags("0x")); // non-hex
2383    }
2384
2385    #[test]
2386    fn parse_traceparent_happy_path() {
2387        assert_eq!(
2388            parse_traceparent("00-11111111111111111111111111111111-2222222222222222-01"),
2389            (
2390                Some("11111111111111111111111111111111".to_string()),
2391                Some("2222222222222222".to_string()),
2392                Some("01".to_string()),
2393            )
2394        );
2395
2396        // Future versions are accepted and unsupported flag bits are cleared.
2397        let (trace_id, _, trace_flags) =
2398            parse_traceparent("01-11111111111111111111111111111111-2222222222222222-09");
2399        assert_eq!(
2400            trace_id.as_deref(),
2401            Some("11111111111111111111111111111111")
2402        );
2403        assert_eq!(trace_flags.as_deref(), Some("01"));
2404    }
2405
2406    #[test]
2407    fn parse_traceparent_rejects_malformed() {
2408        // Wrong number of `-`-separated segments.
2409        assert_eq!(parse_traceparent("00-1111-2222"), (None, None, None)); // 3 segments
2410        assert_eq!(
2411            parse_traceparent("00-11111111111111111111111111111111-2222222222222222-00-extra"),
2412            (None, None, None)
2413        ); // 5 segments
2414
2415        // All-or-nothing: any single invalid field rejects the whole parse.
2416        // (Per-field rules are covered by the is_valid_* tests above.)
2417        for tp in [
2418            "ff-11111111111111111111111111111111-2222222222222222-01", // bad version
2419            "00-bad-2222222222222222-01",                              // bad trace_id
2420            "00-11111111111111111111111111111111-bad-01",              // bad span_id
2421            "00-11111111111111111111111111111111-2222222222222222-0x", // bad flags
2422        ] {
2423            assert_eq!(
2424                parse_traceparent(tp),
2425                (None, None, None),
2426                "should reject: {tp}"
2427            );
2428        }
2429    }
2430
2431    #[test]
2432    fn trace_parent_from_headers_preserves_unsampled_flag() {
2433        let mut headers = async_nats::HeaderMap::new();
2434        headers.insert(
2435            "traceparent",
2436            "00-11111111111111111111111111111111-2222222222222222-00",
2437        );
2438
2439        let trace_parent = TraceParent::from_headers(&headers);
2440
2441        assert_eq!(
2442            trace_parent.trace_id.as_deref(),
2443            Some("11111111111111111111111111111111")
2444        );
2445        assert_eq!(trace_parent.parent_id.as_deref(), Some("2222222222222222"));
2446        assert_eq!(trace_parent.trace_flags.as_deref(), Some("00"));
2447    }
2448
2449    #[test]
2450    fn distributed_context_creates_traceparent_with_stored_flags() {
2451        let context = DistributedTraceContext {
2452            trace_id: "11111111111111111111111111111111".to_string(),
2453            span_id: "2222222222222222".to_string(),
2454            trace_flags: "00".to_string(),
2455            parent_id: None,
2456            tracestate: None,
2457            start: None,
2458            end: None,
2459            x_request_id: None,
2460            request_id: None,
2461        };
2462
2463        assert_eq!(
2464            context.create_traceparent(),
2465            "00-11111111111111111111111111111111-2222222222222222-00"
2466        );
2467    }
2468
2469    #[test]
2470    fn inject_trace_headers_preserves_current_span_flags() {
2471        // Use the core `set_default` (not `SubscriberInitExt::set_default`, which
2472        // also installs the global `log` LogTracer and would poison a later
2473        // `logging::init()` with SetLoggerError).
2474        let _interest_guard = crate::test_utils::tracing_interest_guard();
2475        let _guard = tracing::subscriber::set_default(
2476            tracing_subscriber::registry().with(DistributedTraceIdLayer),
2477        );
2478        let span = tracing::info_span!(
2479            "root",
2480            trace_id = "11111111111111111111111111111111",
2481            span_id = "2222222222222222",
2482            trace_flags = "00"
2483        );
2484        let _enter = span.enter();
2485        let mut headers = std::collections::HashMap::new();
2486
2487        inject_trace_headers_into_map(&mut headers);
2488
2489        assert_eq!(
2490            headers.get("traceparent").map(String::as_str),
2491            Some("00-11111111111111111111111111111111-2222222222222222-00")
2492        );
2493    }
2494
2495    #[test]
2496    fn request_span_preserves_inbound_trace_flags() {
2497        // Use the core `set_default` (not `SubscriberInitExt::set_default`, which
2498        // also installs the global `log` LogTracer and would poison a later
2499        // `logging::init()` with SetLoggerError).
2500        let _interest_guard = crate::test_utils::tracing_interest_guard();
2501        let _guard = tracing::subscriber::set_default(
2502            tracing_subscriber::registry().with(DistributedTraceIdLayer),
2503        );
2504        let req = Request::builder()
2505            .header(
2506                "traceparent",
2507                "00-11111111111111111111111111111111-2222222222222222-00",
2508            )
2509            .body(())
2510            .unwrap();
2511        let trace_parent = TraceParent::from_headers(req.headers());
2512        let span = tracing::info_span!(
2513            "root",
2514            trace_id = trace_parent.trace_id,
2515            span_id = "3333333333333333",
2516            parent_id = trace_parent.parent_id,
2517            trace_flags = trace_parent.trace_flags
2518        );
2519        let _enter = span.enter();
2520        let mut headers = std::collections::HashMap::new();
2521
2522        inject_trace_headers_into_map(&mut headers);
2523
2524        assert_eq!(
2525            headers.get("traceparent").map(String::as_str),
2526            Some("00-11111111111111111111111111111111-3333333333333333-00")
2527        );
2528    }
2529
2530    #[test]
2531    fn http_request_spans_mint_request_id_and_ignore_client_headers() {
2532        let provider = SdkTracerProvider::builder().build();
2533        let tracer = provider.tracer("test");
2534        // Core `set_default`: `SubscriberInitExt::set_default` installs the global `log`
2535        // LogTracer, which would make a later `logging::init()` fail with SetLoggerError.
2536        let _guard = tracing::subscriber::set_default(
2537            tracing_subscriber::registry()
2538                .with(tracing_opentelemetry::layer().with_tracer(tracer))
2539                .with(DistributedTraceIdLayer),
2540        );
2541        let client_id = "11111111-2222-3333-4444-555555555555";
2542        let make_req = || {
2543            Request::builder()
2544                .header("request-id", client_id)
2545                .header("x-dynamo-request-id", client_id)
2546                .header("x-request-id", "client-correlation")
2547                .body(())
2548                .unwrap()
2549        };
2550
2551        let mut seen = Vec::new();
2552        for make_span in [
2553            make_inference_request_span::<()>,
2554            make_inference_request_span::<()>,
2555            make_system_request_span::<()>,
2556        ] {
2557            let span = make_span(&make_req());
2558            let _enter = span.enter();
2559            let ctx = get_distributed_tracing_context().expect("span has trace context");
2560            let request_id = ctx.request_id.expect("span has a request_id");
2561            assert_ne!(request_id, client_id);
2562            assert!(Uuid::parse_str(&request_id).is_ok());
2563            assert_eq!(ctx.x_request_id.as_deref(), Some("client-correlation"));
2564            seen.push(request_id);
2565        }
2566        assert_ne!(seen[0], seen[1], "each HTTP request must get its own id");
2567
2568        let trace_parent = TraceParent::from_headers(make_req().headers());
2569        assert_eq!(trace_parent.request_id.as_deref(), Some(client_id));
2570    }
2571
2572    #[test]
2573    fn root_context_uses_otel_unsampled_decision() {
2574        let provider = SdkTracerProvider::builder()
2575            .with_sampler(opentelemetry_sdk::trace::Sampler::AlwaysOff)
2576            .build();
2577        let tracer = provider.tracer("test");
2578        // Core `set_default` (not `SubscriberInitExt::set_default`) to avoid
2579        // installing the global `log` LogTracer, which would poison a later
2580        // `logging::init()` with SetLoggerError.
2581        let _interest_guard = crate::test_utils::tracing_interest_guard();
2582        let _guard = tracing::subscriber::set_default(
2583            tracing_subscriber::registry()
2584                .with(tracing_opentelemetry::layer().with_tracer(tracer))
2585                .with(DistributedTraceIdLayer),
2586        );
2587        let span = tracing::info_span!("root");
2588        let _enter = span.enter();
2589        let mut headers = std::collections::HashMap::new();
2590
2591        inject_trace_headers_into_map(&mut headers);
2592
2593        assert!(headers["traceparent"].ends_with("-00"));
2594        assert_eq!(
2595            get_distributed_tracing_context()
2596                .as_ref()
2597                .map(|ctx| ctx.trace_flags.as_str()),
2598            Some("00")
2599        );
2600    }
2601
2602    #[test]
2603    fn root_context_uses_otel_sampled_decision() {
2604        let provider = SdkTracerProvider::builder()
2605            .with_sampler(opentelemetry_sdk::trace::Sampler::AlwaysOn)
2606            .build();
2607        let tracer = provider.tracer("test");
2608        // Core `set_default` (not `SubscriberInitExt::set_default`) to avoid
2609        // installing the global `log` LogTracer, which would poison a later
2610        // `logging::init()` with SetLoggerError.
2611        let _interest_guard = crate::test_utils::tracing_interest_guard();
2612        let _guard = tracing::subscriber::set_default(
2613            tracing_subscriber::registry()
2614                .with(tracing_opentelemetry::layer().with_tracer(tracer))
2615                .with(DistributedTraceIdLayer),
2616        );
2617        let span = tracing::info_span!("root");
2618        let _enter = span.enter();
2619        let mut headers = std::collections::HashMap::new();
2620
2621        inject_trace_headers_into_map(&mut headers);
2622
2623        assert!(headers["traceparent"].ends_with("-01"));
2624        assert_eq!(
2625            get_distributed_tracing_context()
2626                .as_ref()
2627                .map(|ctx| ctx.trace_flags.as_str()),
2628            Some("01")
2629        );
2630    }
2631
2632    #[tokio::test]
2633    async fn test_json_log_capture() -> Result<()> {
2634        #[allow(clippy::redundant_closure_call)]
2635        let _ = temp_env::async_with_vars(
2636            [(env_logging::DYN_LOGGING_JSONL, Some("1"))],
2637            (async || {
2638                let tmp_file = NamedTempFile::new().unwrap();
2639                let file_name = tmp_file.path().to_str().unwrap();
2640                let guard = StderrOverride::from_file(file_name)?;
2641                init();
2642                parent().await;
2643                drop(guard);
2644
2645                let lines = load_log(file_name)?;
2646
2647                // 1. Extract the dynamically generated trace ID and validate consistency
2648                // All logs should have the same trace_id since they're part of the same trace
2649                // Skip any initialization logs that don't have trace_id (e.g., OTLP setup messages)
2650                //
2651                // Note: This test can fail if logging was already initialized by another test running
2652                // in parallel. Logging initialization is global (Once) and can only happen once per process.
2653                // If no trace_id is found, skip validation gracefully.
2654                let Some(trace_id) = lines
2655                    .iter()
2656                    .find_map(|log_line| log_line.get("trace_id").and_then(|v| v.as_str()))
2657                    .map(|s| s.to_string())
2658                else {
2659                    // Skip test if logging was already initialized - we can't control the output format
2660                    return Ok(());
2661                };
2662
2663                // Verify trace_id is not a zero/invalid ID
2664                assert_ne!(
2665                    trace_id, "00000000000000000000000000000000",
2666                    "trace_id should not be a zero/invalid ID"
2667                );
2668                assert!(
2669                    !trace_id.chars().all(|c| c == '0'),
2670                    "trace_id should not be all zeros"
2671                );
2672
2673                // Verify all logs have the same trace_id
2674                for log_line in &lines {
2675                    if let Some(line_trace_id) = log_line.get("trace_id") {
2676                        assert_eq!(
2677                            line_trace_id.as_str().unwrap(),
2678                            &trace_id,
2679                            "All logs should have the same trace_id"
2680                        );
2681                    }
2682                }
2683
2684                // Validate my_trace_id matches the actual trace ID
2685                for log_line in &lines {
2686                    if let Some(my_trace_id) = log_line.get("my_trace_id") {
2687                        assert_eq!(
2688                            my_trace_id,
2689                            &serde_json::Value::String(trace_id.clone()),
2690                            "my_trace_id should match the trace_id from distributed tracing context"
2691                        );
2692                    }
2693                }
2694
2695                // 2. Validate span IDs exist and are properly formatted
2696                let mut span_ids_seen: std::collections::HashSet<String> = std::collections::HashSet::new();
2697                let mut span_timestamps: std::collections::HashMap<String, DateTime<Utc>> = std::collections::HashMap::new();
2698
2699                for log_line in &lines {
2700                    if let Some(span_id) = log_line.get("span_id") {
2701                        let span_id_str = span_id.as_str().unwrap();
2702                        assert!(
2703                            is_valid_span_id(span_id_str),
2704                            "Invalid span_id format: {}",
2705                            span_id_str
2706                        );
2707                        span_ids_seen.insert(span_id_str.to_string());
2708                    }
2709
2710                    // Validate timestamp format and track span timestamps
2711                    if let Some(time_str) = log_line.get("time").and_then(|v| v.as_str()) {
2712                        let timestamp = DateTime::parse_from_rfc3339(time_str)
2713                            .expect("All timestamps should be valid RFC3339 format")
2714                            .with_timezone(&Utc);
2715
2716                        // Track timestamp for each span_name
2717                        if let Some(span_name) = log_line.get("span_name").and_then(|v| v.as_str()) {
2718                            span_timestamps.insert(span_name.to_string(), timestamp);
2719                        }
2720                    }
2721                }
2722
2723                // 3. Validate parent-child span relationships
2724                // Extract span IDs for each span by looking at their log messages
2725                let parent_span_id = lines
2726                    .iter()
2727                    .find(|log_line| {
2728                        log_line.get("span_name")
2729                            .and_then(|v| v.as_str()) == Some("parent")
2730                    })
2731                    .and_then(|log_line| {
2732                        log_line.get("span_id")
2733                            .and_then(|v| v.as_str())
2734                            .map(|s| s.to_string())
2735                    })
2736                    .expect("Should find parent span with span_id");
2737
2738                let child_span_id = lines
2739                    .iter()
2740                    .find(|log_line| {
2741                        log_line.get("span_name")
2742                            .and_then(|v| v.as_str()) == Some("child")
2743                    })
2744                    .and_then(|log_line| {
2745                        log_line.get("span_id")
2746                            .and_then(|v| v.as_str())
2747                            .map(|s| s.to_string())
2748                    })
2749                    .expect("Should find child span with span_id");
2750
2751                let grandchild_span_id = lines
2752                    .iter()
2753                    .find(|log_line| {
2754                        log_line.get("span_name")
2755                            .and_then(|v| v.as_str()) == Some("grandchild")
2756                    })
2757                    .and_then(|log_line| {
2758                        log_line.get("span_id")
2759                            .and_then(|v| v.as_str())
2760                            .map(|s| s.to_string())
2761                    })
2762                    .expect("Should find grandchild span with span_id");
2763
2764                // Verify span IDs are unique
2765                assert_ne!(parent_span_id, child_span_id, "Parent and child should have different span IDs");
2766                assert_ne!(child_span_id, grandchild_span_id, "Child and grandchild should have different span IDs");
2767                assert_ne!(parent_span_id, grandchild_span_id, "Parent and grandchild should have different span IDs");
2768
2769                // Verify parent span has no parent_id
2770                for log_line in &lines {
2771                    if let Some(span_name) = log_line.get("span_name")
2772                        && let Some(span_name_str) = span_name.as_str()
2773                        && span_name_str == "parent"
2774                    {
2775                        assert!(
2776                            log_line.get("parent_id").is_none(),
2777                            "Parent span should not have a parent_id"
2778                        );
2779                    }
2780                }
2781
2782                // Verify child span's parent_id is parent_span_id
2783                for log_line in &lines {
2784                    if let Some(span_name) = log_line.get("span_name")
2785                        && let Some(span_name_str) = span_name.as_str()
2786                        && span_name_str == "child"
2787                    {
2788                        let parent_id = log_line.get("parent_id")
2789                            .and_then(|v| v.as_str())
2790                            .expect("Child span should have a parent_id");
2791                        assert_eq!(
2792                            parent_id,
2793                            parent_span_id,
2794                            "Child's parent_id should match parent's span_id"
2795                        );
2796                    }
2797                }
2798
2799                // Verify grandchild span's parent_id is child_span_id
2800                for log_line in &lines {
2801                    if let Some(span_name) = log_line.get("span_name")
2802                        && let Some(span_name_str) = span_name.as_str()
2803                        && span_name_str == "grandchild"
2804                    {
2805                        let parent_id = log_line.get("parent_id")
2806                            .and_then(|v| v.as_str())
2807                            .expect("Grandchild span should have a parent_id");
2808                        assert_eq!(
2809                            parent_id,
2810                            child_span_id,
2811                            "Grandchild's parent_id should match child's span_id"
2812                        );
2813                    }
2814                }
2815
2816                // 4. Validate timestamp ordering - spans should log in execution order
2817                let parent_time = span_timestamps.get("parent")
2818                    .expect("Should have timestamp for parent span");
2819                let child_time = span_timestamps.get("child")
2820                    .expect("Should have timestamp for child span");
2821                let grandchild_time = span_timestamps.get("grandchild")
2822                    .expect("Should have timestamp for grandchild span");
2823
2824                // Parent logs first (or at same time), then child, then grandchild
2825                assert!(
2826                    parent_time <= child_time,
2827                    "Parent span should log before or at same time as child span (parent: {}, child: {})",
2828                    parent_time,
2829                    child_time
2830                );
2831                assert!(
2832                    child_time <= grandchild_time,
2833                    "Child span should log before or at same time as grandchild span (child: {}, grandchild: {})",
2834                    child_time,
2835                    grandchild_time
2836                );
2837
2838                Ok::<(), anyhow::Error>(())
2839            })(),
2840        )
2841        .await;
2842        Ok(())
2843    }
2844
2845    #[test]
2846    fn test_otlp_export_works_without_json_logging() {
2847        use std::process::Command;
2848
2849        let output = Command::new("cargo")
2850            .args([
2851                "test",
2852                "-p",
2853                "dynamo-runtime",
2854                "logging::tests::test_otlp_export_without_json_logging_subprocess",
2855                "--",
2856                "--exact",
2857                "--nocapture",
2858            ])
2859            .env("OTEL_EXPORT_ENABLED", "1")
2860            .env_remove("DYN_LOGGING_CONSOLE_FORMAT")
2861            .env_remove("DYN_LOGGING_JSONL")
2862            .output()
2863            .expect("Failed to execute subprocess test");
2864
2865        let stderr = String::from_utf8_lossy(&output.stderr);
2866        if !output.status.success() {
2867            eprintln!(
2868                "=== STDOUT ===\n{}",
2869                String::from_utf8_lossy(&output.stdout)
2870            );
2871            eprintln!("=== STDERR ===\n{}", stderr);
2872        }
2873
2874        assert!(
2875            output.status.success(),
2876            "Subprocess test failed with exit code: {:?}",
2877            output.status.code()
2878        );
2879        assert!(
2880            !stderr.contains("has no effect without DYN_LOGGING_JSONL"),
2881            "OTLP export should not depend on JSONL logging: {stderr}"
2882        );
2883        assert!(
2884            stderr.contains("OpenTelemetry OTLP export enabled"),
2885            "OTLP export should initialize with readable logging: {stderr}"
2886        );
2887    }
2888
2889    #[tokio::test]
2890    async fn test_otlp_export_without_json_logging_subprocess() {
2891        if std::env::var("OTEL_EXPORT_ENABLED").is_err() {
2892            return;
2893        }
2894
2895        init();
2896        tracing::info!("readable log with OTLP export");
2897    }
2898
2899    #[test]
2900    fn otlp_sync_init_connects_without_ambient_runtime() {
2901        use std::process::Command;
2902        use std::time::Duration;
2903
2904        // Both settings — JSONL=1 + OTEL=1 is the combo that used to panic.
2905        for jsonl in ["0", "1"] {
2906            // (a) Parent owns a TCP listener; the child's exporter must connect to it.
2907            //     Port 0 = "OS, pick any free port", then read back which one.
2908            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind loopback");
2909            let addr = listener.local_addr().expect("get local addr");
2910
2911            // (b) Accept ONE connection on a helper thread; tell us via a channel.
2912            let (tx, rx) = std::sync::mpsc::channel();
2913            let accept = std::thread::spawn(move || {
2914                if listener.accept().is_ok() {
2915                    let _ = tx.send(()); // signal "a connection arrived"
2916                }
2917            });
2918
2919            // (c) Re-run as a fresh subprocess, running ONLY the child test.
2920            let output = Command::new("cargo")
2921                .args([
2922                    "test",
2923                    "-p",
2924                    "dynamo-runtime",
2925                    "logging::tests::otlp_sync_init_connects_subprocess",
2926                    "--",
2927                    "--exact",
2928                    "--nocapture",
2929                ])
2930                .env("OTEL_EXPORT_ENABLED", "1")
2931                .env("DYN_LOGGING_JSONL", jsonl)
2932                .env("OTEL_EXPORTER_OTLP_ENDPOINT", format!("http://{addr}"))
2933                // Don't let host-inherited per-signal overrides redirect an exporter
2934                // away from our listener or change its protocol.
2935                .env_remove("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")
2936                .env_remove("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT")
2937                .env_remove("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL")
2938                .env_remove("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL")
2939                .env("OTEL_BSP_SCHEDULE_DELAY", "100") // flush fast (ms) so it connects promptly
2940                .output()
2941                .expect("failed to run subprocess");
2942
2943            // (d) it must NOT panic, for both JSONL modes.
2944            assert!(
2945                output.status.success(),
2946                "sync init subprocess (JSONL={jsonl}) failed:\n{}",
2947                String::from_utf8_lossy(&output.stderr),
2948            );
2949
2950            // (e) The real proof: the exporter actually connected → the persistent
2951            //     runtime is alive and DRIVEN.
2952            rx.recv_timeout(Duration::from_secs(10))
2953                .unwrap_or_else(|_| {
2954                    panic!("exporter never connected (JSONL={jsonl}); export runtime not driven")
2955                });
2956
2957            let _ = accept.join(); // let the helper thread finish
2958        }
2959    }
2960
2961    #[test]
2962    fn otlp_sync_init_connects_subprocess() {
2963        // When run by a normal `cargo test`, OTEL_EXPORT_ENABLED isn't set → do nothing.
2964        // The parent sets it, so only then do we run the real body.
2965        if std::env::var("OTEL_EXPORT_ENABLED").is_err() {
2966            return;
2967        }
2968
2969        assert!(
2970            tokio::runtime::Handle::try_current().is_err(),
2971            "subprocess must run with no ambient Tokio runtime",
2972        );
2973
2974        init(); // real global init → setup_logging → otel_runtime_handle
2975
2976        // Emit real span + log data. Close the span (drop the guard) BEFORE the
2977        // wait below: a span is only exported when it ends, so an open span would
2978        // leave the batch trace exporter with nothing to flush in the window.
2979        {
2980            let _span = tracing::info_span!("otlp_sync_smoke").entered();
2981            tracing::info!("otlp sync-init smoke log");
2982        }
2983
2984        // Give the batch exporter's scheduled flush time to fire and connect.
2985        std::thread::sleep(std::time::Duration::from_secs(2));
2986    }
2987
2988    // Test functions at different log levels for filtering tests
2989    #[tracing::instrument(level = "debug", skip_all)]
2990    async fn debug_level_span() {
2991        tracing::debug!("inside debug span");
2992    }
2993
2994    #[tracing::instrument(level = "info", skip_all)]
2995    async fn info_level_span() {
2996        tracing::info!("inside info span");
2997    }
2998
2999    #[tracing::instrument(level = "warn", skip_all)]
3000    async fn warn_level_span() {
3001        tracing::warn!("inside warn span");
3002    }
3003
3004    // Span from a different target - should be FILTERED OUT at info level
3005    // because the filter is warn,dynamo_runtime::logging::tests=debug
3006    #[tracing::instrument(level = "info", target = "other_module", skip_all)]
3007    async fn other_target_info_span() {
3008        tracing::info!(target: "other_module", "inside other target span");
3009    }
3010
3011    /// Headers must reach the gRPC exporters. `opentelemetry-otlp` reads
3012    /// OTEL_EXPORTER_OTLP_HEADERS only on its HTTP path, and Dynamo defaults to
3013    /// gRPC, so without explicit metadata an authenticated collector rejects
3014    /// every span and log while the variable looks configured.
3015    #[test]
3016    fn otlp_headers_reach_the_grpc_exporters() {
3017        temp_env::with_vars(
3018            [
3019                (
3020                    env_logging::otlp::OTEL_EXPORTER_OTLP_HEADERS,
3021                    Some("authorization=Bearer abc=="),
3022                ),
3023                (env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_HEADERS, None),
3024            ],
3025            || {
3026                let md = otlp_metadata_for(env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_HEADERS);
3027                assert_eq!(
3028                    md.get("authorization").map(|v| v.to_str().unwrap()),
3029                    Some("Bearer abc==")
3030                );
3031            },
3032        );
3033
3034        // Signal-specific replaces the generic set rather than merging.
3035        temp_env::with_vars(
3036            [
3037                (
3038                    env_logging::otlp::OTEL_EXPORTER_OTLP_HEADERS,
3039                    Some("generic=1"),
3040                ),
3041                (
3042                    env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_HEADERS,
3043                    Some("specific=2"),
3044                ),
3045            ],
3046            || {
3047                let md = otlp_metadata_for(env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_HEADERS);
3048                assert!(md.get("generic").is_none(), "generic should not be merged");
3049                assert_eq!(md.get("specific").map(|v| v.to_str().unwrap()), Some("2"));
3050            },
3051        );
3052    }
3053
3054    #[test]
3055    fn test_readable_console_with_otel_export() {
3056        use std::process::Command;
3057
3058        let output = Command::new("cargo")
3059            .args([
3060                "test",
3061                "-p",
3062                "dynamo-runtime",
3063                "logging::tests::test_readable_console_with_otel_export_subprocess",
3064                "--",
3065                "--exact",
3066                "--nocapture",
3067            ])
3068            .env("DYN_TEST_LOGGING_READABLE_OTEL", "1")
3069            .env("DYN_LOGGING_CONSOLE_FORMAT", "readable")
3070            .env("DYN_LOGGING_JSONL", "1")
3071            .env("OTEL_EXPORT_ENABLED", "1")
3072            .env("DYN_LOG", "info")
3073            .env("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", DEFAULT_OTLP_ENDPOINT)
3074            .env("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", DEFAULT_OTLP_ENDPOINT)
3075            .output()
3076            .expect("Failed to execute subprocess test");
3077
3078        if !output.status.success() {
3079            eprintln!(
3080                "=== STDOUT ===\n{}",
3081                String::from_utf8_lossy(&output.stdout)
3082            );
3083            eprintln!(
3084                "=== STDERR ===\n{}",
3085                String::from_utf8_lossy(&output.stderr)
3086            );
3087        }
3088
3089        assert!(
3090            output.status.success(),
3091            "Subprocess test failed with exit code: {:?}",
3092            output.status.code()
3093        );
3094    }
3095
3096    #[tokio::test]
3097    async fn test_readable_console_with_otel_export_subprocess() -> Result<()> {
3098        if std::env::var("DYN_TEST_LOGGING_READABLE_OTEL").is_err() {
3099            return Ok(());
3100        }
3101
3102        let tmp_file = NamedTempFile::new().unwrap();
3103        let file_name = tmp_file.path().to_str().unwrap();
3104        let guard = StderrOverride::from_file(file_name)?;
3105        init();
3106        tracing::info!("readable console with otel marker");
3107        drop(guard);
3108
3109        let content = std::fs::read_to_string(file_name)?;
3110        assert!(
3111            content.contains("OpenTelemetry OTLP export enabled"),
3112            "expected OTLP init log in captured stderr, got: {content}"
3113        );
3114        assert!(
3115            content.contains("readable console with otel marker"),
3116            "expected marker log in captured stderr, got: {content}"
3117        );
3118
3119        for line in content.lines().filter(|line| !line.trim().is_empty()) {
3120            assert!(
3121                serde_json::from_str::<Value>(line).is_err(),
3122                "expected readable log line, got JSON: {line}"
3123            );
3124        }
3125
3126        Ok(())
3127    }
3128
3129    #[test]
3130    fn test_tokio_console_respects_console_format() {
3131        use std::process::Command;
3132
3133        let output = Command::new("cargo")
3134            .args([
3135                "test",
3136                "-p",
3137                "dynamo-runtime",
3138                "--features",
3139                "tokio-console",
3140                "logging::tests::test_tokio_console_respects_console_format_subprocess",
3141                "--",
3142                "--exact",
3143                "--nocapture",
3144            ])
3145            .env("DYN_TEST_LOGGING_TOKIO_CONSOLE_JSONL", "1")
3146            .env("DYN_LOGGING_CONSOLE_FORMAT", "jsonl")
3147            .env_remove("DYN_LOGGING_JSONL")
3148            .env_remove("OTEL_EXPORT_ENABLED")
3149            .env("DYN_LOG", "info")
3150            .output()
3151            .expect("Failed to execute subprocess test");
3152
3153        if !output.status.success() {
3154            eprintln!(
3155                "=== STDOUT ===\n{}",
3156                String::from_utf8_lossy(&output.stdout)
3157            );
3158            eprintln!(
3159                "=== STDERR ===\n{}",
3160                String::from_utf8_lossy(&output.stderr)
3161            );
3162        }
3163
3164        assert!(
3165            output.status.success(),
3166            "Subprocess test failed with exit code: {:?}",
3167            output.status.code()
3168        );
3169    }
3170
3171    #[tokio::test]
3172    async fn test_tokio_console_respects_console_format_subprocess() -> Result<()> {
3173        if std::env::var("DYN_TEST_LOGGING_TOKIO_CONSOLE_JSONL").is_err() {
3174            return Ok(());
3175        }
3176
3177        let tmp_file = NamedTempFile::new().unwrap();
3178        let file_name = tmp_file.path().to_str().unwrap();
3179        let guard = StderrOverride::from_file(file_name)?;
3180        init();
3181        tracing::info!("tokio console jsonl marker");
3182        drop(guard);
3183
3184        let content = std::fs::read_to_string(file_name)?;
3185        let marker_line = content
3186            .lines()
3187            .find(|line| line.contains("tokio console jsonl marker"))
3188            .unwrap_or_else(|| panic!("expected marker log in captured stderr, got: {content}"));
3189        serde_json::from_str::<Value>(marker_line)
3190            .unwrap_or_else(|error| panic!("expected JSONL marker, got '{marker_line}': {error}"));
3191
3192        Ok(())
3193    }
3194
3195    #[test]
3196    fn test_readable_console_preserves_legacy_trace_context() {
3197        use std::process::Command;
3198
3199        let output = Command::new("cargo")
3200            .args([
3201                "test",
3202                "-p",
3203                "dynamo-runtime",
3204                "logging::tests::test_readable_console_preserves_legacy_trace_context_subprocess",
3205                "--",
3206                "--exact",
3207                "--nocapture",
3208            ])
3209            .env("DYN_TEST_LOGGING_READABLE_LEGACY_TRACE", "1")
3210            .env("DYN_LOGGING_CONSOLE_FORMAT", "readable")
3211            .env("DYN_LOGGING_JSONL", "1")
3212            .env_remove("OTEL_EXPORT_ENABLED")
3213            .env("DYN_LOG", "info")
3214            .output()
3215            .expect("Failed to execute subprocess test");
3216
3217        if !output.status.success() {
3218            eprintln!(
3219                "=== STDOUT ===\n{}",
3220                String::from_utf8_lossy(&output.stdout)
3221            );
3222            eprintln!(
3223                "=== STDERR ===\n{}",
3224                String::from_utf8_lossy(&output.stderr)
3225            );
3226        }
3227
3228        assert!(
3229            output.status.success(),
3230            "Subprocess test failed with exit code: {:?}",
3231            output.status.code()
3232        );
3233    }
3234
3235    #[tokio::test]
3236    async fn test_readable_console_preserves_legacy_trace_context_subprocess() -> Result<()> {
3237        if std::env::var("DYN_TEST_LOGGING_READABLE_LEGACY_TRACE").is_err() {
3238            return Ok(());
3239        }
3240
3241        let tmp_file = NamedTempFile::new().unwrap();
3242        let file_name = tmp_file.path().to_str().unwrap();
3243        let guard = StderrOverride::from_file(file_name)?;
3244        init();
3245
3246        let span = tracing::info_span!("legacy_trace_context");
3247        let trace_context = span.in_scope(get_distributed_tracing_context);
3248        assert!(
3249            trace_context.is_some(),
3250            "legacy DYN_LOGGING_JSONL should keep local trace context enabled"
3251        );
3252
3253        let mut headers = HashMap::new();
3254        span.in_scope(|| inject_trace_headers_into_map(&mut headers));
3255        assert!(
3256            headers.contains_key("traceparent"),
3257            "legacy trace context should remain available for propagation"
3258        );
3259
3260        tracing::info!("readable console with legacy trace marker");
3261        drop(guard);
3262
3263        let content = std::fs::read_to_string(file_name)?;
3264        assert!(
3265            content.contains("readable console with legacy trace marker"),
3266            "expected marker log in captured stderr, got: {content}"
3267        );
3268        for line in content.lines().filter(|line| !line.trim().is_empty()) {
3269            assert!(
3270                serde_json::from_str::<Value>(line).is_err(),
3271                "expected readable log line, got JSON: {line}"
3272            );
3273        }
3274
3275        Ok(())
3276    }
3277
3278    /// Comprehensive test for span events covering:
3279    /// - SPAN_FIRST_ENTRY and SPAN_CLOSED event emission
3280    /// - Trace context (trace_id, span_id) in span events
3281    /// - Timing information in SPAN_CLOSED events
3282    /// - Level-based filtering (positive: allowed levels pass, negative: filtered levels blocked)
3283    /// - Target-based filtering (spans from allowed targets pass even at lower levels)
3284    ///
3285    /// This test runs in a subprocess to ensure logging is initialized with our specific
3286    /// filter settings (DYN_LOG=warn,dynamo_runtime::logging::tests=debug), avoiding
3287    /// interference from other tests that may have initialized logging first.
3288    #[test]
3289    fn test_span_events() {
3290        use std::process::Command;
3291
3292        // Run cargo test for the subprocess test with specific env vars
3293        let output = Command::new("cargo")
3294            .args([
3295                "test",
3296                "-p",
3297                "dynamo-runtime",
3298                "logging::tests::test_span_events_subprocess",
3299                "--",
3300                "--exact",
3301                "--nocapture",
3302            ])
3303            .env("DYN_LOGGING_CONSOLE_FORMAT", "jsonl")
3304            .env("DYN_LOGGING_JSONL", "1")
3305            .env("DYN_LOGGING_SPAN_EVENTS", "1")
3306            .env("DYN_LOG", "warn,dynamo_runtime::logging::tests=debug")
3307            .output()
3308            .expect("Failed to execute subprocess test");
3309
3310        // Print output for debugging
3311        if !output.status.success() {
3312            eprintln!(
3313                "=== STDOUT ===\n{}",
3314                String::from_utf8_lossy(&output.stdout)
3315            );
3316            eprintln!(
3317                "=== STDERR ===\n{}",
3318                String::from_utf8_lossy(&output.stderr)
3319            );
3320        }
3321
3322        assert!(
3323            output.status.success(),
3324            "Subprocess test failed with exit code: {:?}",
3325            output.status.code()
3326        );
3327    }
3328
3329    /// Subprocess test that performs the actual span event validation.
3330    /// This is called by test_span_events in a separate process with controlled env vars.
3331    #[tokio::test]
3332    async fn test_span_events_subprocess() -> Result<()> {
3333        // Skip if not running as subprocess (env vars not set)
3334        if std::env::var("DYN_LOGGING_SPAN_EVENTS").is_err() {
3335            return Ok(());
3336        }
3337
3338        let tmp_file = NamedTempFile::new().unwrap();
3339        let file_name = tmp_file.path().to_str().unwrap();
3340        let guard = StderrOverride::from_file(file_name)?;
3341        init();
3342
3343        // Trace context without OTLP export must keep levels below `DYN_LOG` disabled.
3344        assert!(!tracing::enabled!(tracing::Level::TRACE));
3345
3346        // Run parent/child/grandchild spans (all INFO level by default)
3347        parent().await;
3348
3349        // Run spans at explicit levels from our test module
3350        debug_level_span().await;
3351        info_level_span().await;
3352        warn_level_span().await;
3353
3354        // Run span from different target (should be filtered out)
3355        other_target_info_span().await;
3356
3357        drop(guard);
3358
3359        let lines = load_log(file_name)?;
3360
3361        // Helper to check if a span event exists
3362        let has_span_event = |msg: &str, span_name: &str| {
3363            lines.iter().any(|log| {
3364                log.get("message").and_then(|v| v.as_str()) == Some(msg)
3365                    && log.get("span_name").and_then(|v| v.as_str()) == Some(span_name)
3366            })
3367        };
3368
3369        // Helper to get span events
3370        let get_span_events = |msg: &str| -> Vec<&serde_json::Value> {
3371            lines
3372                .iter()
3373                .filter(|log| log.get("message").and_then(|v| v.as_str()) == Some(msg))
3374                .collect()
3375        };
3376
3377        // === Test 1: SPAN_FIRST_ENTRY events have required fields ===
3378        let span_created_events = get_span_events("SPAN_FIRST_ENTRY");
3379        for event in &span_created_events {
3380            // Must have span_name
3381            assert!(
3382                event.get("span_name").is_some(),
3383                "SPAN_FIRST_ENTRY must have span_name"
3384            );
3385            // Must have valid trace_id (format check)
3386            let trace_id = event
3387                .get("trace_id")
3388                .and_then(|v| v.as_str())
3389                .expect("SPAN_FIRST_ENTRY must have trace_id");
3390            assert!(
3391                trace_id.len() == 32 && trace_id.chars().all(|c| c.is_ascii_hexdigit()),
3392                "SPAN_FIRST_ENTRY must have valid trace_id format"
3393            );
3394            // Must have valid span_id
3395            let span_id = event
3396                .get("span_id")
3397                .and_then(|v| v.as_str())
3398                .expect("SPAN_FIRST_ENTRY must have span_id");
3399            assert!(
3400                is_valid_span_id(span_id),
3401                "SPAN_FIRST_ENTRY must have valid span_id"
3402            );
3403        }
3404
3405        // === Test 2: SPAN_CLOSED events have timing info ===
3406        let span_closed_events = get_span_events("SPAN_CLOSED");
3407        for event in &span_closed_events {
3408            assert!(
3409                event.get("span_name").is_some(),
3410                "SPAN_CLOSED must have span_name"
3411            );
3412            assert!(
3413                event.get("time.busy_us").is_some()
3414                    || event.get("time.idle_us").is_some()
3415                    || event.get("time.duration_us").is_some(),
3416                "SPAN_CLOSED must have timing information"
3417            );
3418            // Must have valid trace_id
3419            let trace_id = event
3420                .get("trace_id")
3421                .and_then(|v| v.as_str())
3422                .expect("SPAN_CLOSED must have trace_id");
3423            assert!(
3424                trace_id.len() == 32 && trace_id.chars().all(|c| c.is_ascii_hexdigit()),
3425                "SPAN_CLOSED must have valid trace_id format"
3426            );
3427        }
3428
3429        // === Test 3: Target-based filtering (positive) ===
3430        // Spans from dynamo_runtime::logging::tests should pass at ALL levels
3431        // because the target is allowed at debug level
3432        assert!(
3433            has_span_event("SPAN_FIRST_ENTRY", "debug_level_span"),
3434            "DEBUG span from allowed target MUST pass (target=debug filter)"
3435        );
3436        assert!(
3437            has_span_event("SPAN_FIRST_ENTRY", "info_level_span"),
3438            "INFO span from allowed target MUST pass (target=debug filter)"
3439        );
3440        assert!(
3441            has_span_event("SPAN_FIRST_ENTRY", "warn_level_span"),
3442            "WARN span from allowed target MUST pass (target=debug filter)"
3443        );
3444
3445        // parent/child/grandchild are INFO level from allowed target - should pass
3446        assert!(
3447            has_span_event("SPAN_FIRST_ENTRY", "parent"),
3448            "parent span (INFO) from allowed target MUST pass"
3449        );
3450        assert!(
3451            has_span_event("SPAN_FIRST_ENTRY", "child"),
3452            "child span (INFO) from allowed target MUST pass"
3453        );
3454        assert!(
3455            has_span_event("SPAN_FIRST_ENTRY", "grandchild"),
3456            "grandchild span (INFO) from allowed target MUST pass"
3457        );
3458
3459        // === Test 4: Level-based filtering (negative) ===
3460        // Verify spans from OTHER targets at debug/info level are filtered out
3461        assert!(
3462            !has_span_event("SPAN_FIRST_ENTRY", "other_target_info_span"),
3463            "INFO span from non-allowed target (other_module) MUST be filtered out"
3464        );
3465
3466        // Also verify no spans from other targets appear at debug/info level
3467        for event in &span_created_events {
3468            let target = event.get("target").and_then(|v| v.as_str()).unwrap_or("");
3469            let level = event.get("level").and_then(|v| v.as_str()).unwrap_or("");
3470
3471            // If level is DEBUG or INFO, target must be our test module
3472            if level == "DEBUG" || level == "INFO" {
3473                assert!(
3474                    target.contains("dynamo_runtime::logging::tests"),
3475                    "DEBUG/INFO span must be from allowed target, got target={target}"
3476                );
3477            }
3478        }
3479
3480        Ok(())
3481    }
3482}