"docs/vscode:/vscode.git/clone" did not exist on "9bff03f2375b07dcdca0682ec899b6072dde6747"
logging.rs 73 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
// SPDX-License-Identifier: Apache-2.0

Neelay Shah's avatar
Neelay Shah committed
4
//! Dynamo Distributed Logging Module.
5
6
7
//!
//! - Configuration loaded from:
//!   1. Environment variables (highest priority).
8
//!   2. Optional TOML file pointed to by the `DYN_LOGGING_CONFIG_PATH` environment variable.
Neelay Shah's avatar
Neelay Shah committed
9
//!   3. `/opt/dynamo/etc/logging.toml`.
10
11
//!
//! Logging can take two forms: `READABLE` or `JSONL`. The default is `READABLE`. `JSONL`
12
//! can be enabled by setting the `DYN_LOGGING_JSONL` environment variable to `1`.
13
//!
Ryan Olson's avatar
Ryan Olson committed
14
15
//! To use local timezone for logging timestamps, set the `DYN_LOG_USE_LOCAL_TZ` environment variable to `1`.
//!
16
//! Filters can be configured using the `DYN_LOG` environment variable or by setting the `filters`
17
//! key in the TOML configuration file. Filters are comma-separated key-value pairs where the key
18
//! is the crate or module name and the value is the log level. The default log level is `info`.
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//!
//! Example:
//! ```toml
//! log_level = "error"
//!
//! [log_filters]
//! "test_logging" = "info"
//! "test_logging::api" = "trace"
//! ```

use std::collections::{BTreeMap, HashMap};
use std::sync::Once;

use figment::{
    Figment,
34
    providers::{Format, Serialized, Toml},
35
36
};
use serde::{Deserialize, Serialize};
37
use tracing::level_filters::LevelFilter;
38
use tracing::{Event, Subscriber};
39
use tracing_subscriber::EnvFilter;
Ryan Olson's avatar
Ryan Olson committed
40
41
42
43
use tracing_subscriber::fmt::time::FormatTime;
use tracing_subscriber::fmt::time::LocalTime;
use tracing_subscriber::fmt::time::SystemTime;
use tracing_subscriber::fmt::time::UtcTime;
44
use tracing_subscriber::fmt::{FmtContext, FormatFields};
45
use tracing_subscriber::fmt::{FormattedFields, format::Writer};
46
47
48
49
use tracing_subscriber::prelude::*;
use tracing_subscriber::registry::LookupSpan;
use tracing_subscriber::{filter::Directive, fmt};

50
use crate::config::{disable_ansi_logging, jsonl_logging_enabled, span_events_enabled};
51
use async_nats::{HeaderMap, HeaderValue};
52
use axum::extract::FromRequestParts;
53
54
use axum::http;
use axum::http::Request;
55
use axum::http::request::Parts;
56
57
58
use serde_json::Value;
use std::convert::Infallible;
use std::time::Instant;
59
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
60
61
use tracing::Id;
use tracing::Span;
62
63
64
65
use tracing::field::Field;
use tracing::span;
use tracing_subscriber::Layer;
use tracing_subscriber::Registry;
66
67
68
69
70
use tracing_subscriber::field::Visit;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::layer::Context;
use tracing_subscriber::registry::SpanData;
use uuid::Uuid;
71

72
73
74
use opentelemetry::propagation::{Extractor, Injector, TextMapPropagator};
use opentelemetry::trace::TraceContextExt;
use opentelemetry::{global, trace::Tracer};
75
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
76
77
78
79
80
use opentelemetry_otlp::WithExportConfig;

use opentelemetry::trace::TracerProvider as _;
use opentelemetry::{Key, KeyValue};
use opentelemetry_sdk::Resource;
81
use opentelemetry_sdk::logs::SdkLoggerProvider;
82
83
84
85
86
87
88
89
90
91
use opentelemetry_sdk::trace::SdkTracerProvider;
use tracing::error;
use tracing_subscriber::layer::SubscriberExt;
// use tracing_subscriber::Registry;

use std::time::Duration;
use tracing::{info, instrument};
use tracing_opentelemetry::OpenTelemetrySpanExt;
use tracing_subscriber::util::SubscriberInitExt;

92
use crate::config::environment_names::logging as env_logging;
93

94
95
use dynamo_config::env_is_truthy;

96
/// Default log level
97
const DEFAULT_FILTER_LEVEL: &str = "info";
98

99
100
101
102
103
104
/// Default OTLP endpoint
const DEFAULT_OTLP_ENDPOINT: &str = "http://localhost:4317";

/// Default service name
const DEFAULT_OTEL_SERVICE_NAME: &str = "dynamo";

105
106
107
108
109
110
111
112
113
114
115
116
/// Once instance to ensure the logger is only initialized once
static INIT: Once = Once::new();

#[derive(Serialize, Deserialize, Debug)]
struct LoggingConfig {
    log_level: String,
    log_filters: HashMap<String, String>,
}
impl Default for LoggingConfig {
    fn default() -> Self {
        LoggingConfig {
            log_level: DEFAULT_FILTER_LEVEL.to_string(),
Ryan Olson's avatar
Ryan Olson committed
117
118
119
120
121
122
            log_filters: HashMap::from([
                ("h2".to_string(), "error".to_string()),
                ("tower".to_string(), "error".to_string()),
                ("hyper_util".to_string(), "error".to_string()),
                ("neli".to_string(), "error".to_string()),
                ("async_nats".to_string(), "error".to_string()),
123
124
125
126
127
                ("rustls".to_string(), "error".to_string()),
                ("tokenizers".to_string(), "error".to_string()),
                ("axum".to_string(), "error".to_string()),
                ("tonic".to_string(), "error".to_string()),
                ("hf_hub".to_string(), "error".to_string()),
128
129
130
                ("opentelemetry".to_string(), "error".to_string()),
                ("opentelemetry-otlp".to_string(), "error".to_string()),
                ("opentelemetry_sdk".to_string(), "error".to_string()),
Ryan Olson's avatar
Ryan Olson committed
131
            ]),
132
133
134
135
        }
    }
}

136
/// Check if OTLP trace exporting is enabled (accepts: "1", "true", "on", "yes" - case insensitive)
137
fn otlp_exporter_enabled() -> bool {
138
    env_is_truthy(env_logging::otlp::OTEL_EXPORT_ENABLED)
139
140
}

141
142
/// Get the service name from environment or use default
fn get_service_name() -> String {
143
144
    std::env::var(env_logging::otlp::OTEL_SERVICE_NAME)
        .unwrap_or_else(|_| DEFAULT_OTEL_SERVICE_NAME.to_string())
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
}

/// Validate a given trace ID according to W3C Trace Context specifications.
/// A valid trace ID is a 32-character hexadecimal string (lowercase).
pub fn is_valid_trace_id(trace_id: &str) -> bool {
    trace_id.len() == 32 && trace_id.chars().all(|c| c.is_ascii_hexdigit())
}

/// Validate a given span ID according to W3C Trace Context specifications.
/// A valid span ID is a 16-character hexadecimal string (lowercase).
pub fn is_valid_span_id(span_id: &str) -> bool {
    span_id.len() == 16 && span_id.chars().all(|c| c.is_ascii_hexdigit())
}

pub struct DistributedTraceIdLayer;

161
#[derive(Debug, Clone, Serialize, Deserialize)]
162
pub struct DistributedTraceContext {
163
164
165
166
167
168
169
170
171
    pub trace_id: String,
    pub span_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tracestate: Option<String>,
    #[serde(skip)]
    start: Option<Instant>,
    #[serde(skip)]
172
    end: Option<Instant>,
173
174
175
    #[serde(skip_serializing_if = "Option::is_none")]
    pub x_request_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
176
    pub request_id: Option<String>,
177
178
}

179
180
181
182
183
184
185
186
/// Pending context data collected in on_new_span, to be finalized in on_enter
#[derive(Debug, Clone)]
struct PendingDistributedTraceContext {
    trace_id: Option<String>,
    span_id: Option<String>,
    parent_id: Option<String>,
    tracestate: Option<String>,
    x_request_id: Option<String>,
187
    request_id: Option<String>,
188
189
}

190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/// Macro to emit a tracing event at a dynamic level with a custom target.
macro_rules! emit_at_level {
    ($level:expr, target: $target:expr, $($arg:tt)*) => {
        // tracing::event! requires a compile-time constant level, so we must match
        // on the runtime level and use a literal Level constant in each arm.
        // See: https://github.com/tokio-rs/tracing/issues/2730
        match $level {
            &tracing::Level::ERROR => tracing::event!(target: $target, tracing::Level::ERROR, $($arg)*),
            &tracing::Level::WARN => tracing::event!(target: $target, tracing::Level::WARN, $($arg)*),
            &tracing::Level::INFO => tracing::event!(target: $target, tracing::Level::INFO, $($arg)*),
            &tracing::Level::DEBUG => tracing::event!(target: $target, tracing::Level::DEBUG, $($arg)*),
            &tracing::Level::TRACE => tracing::event!(target: $target, tracing::Level::TRACE, $($arg)*),
        }
    };
}

206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
impl DistributedTraceContext {
    /// Create a traceparent string from the context
    pub fn create_traceparent(&self) -> String {
        format!("00-{}-{}-01", self.trace_id, self.span_id)
    }
}

/// Parse a traceparent string into its components
pub fn parse_traceparent(traceparent: &str) -> (Option<String>, Option<String>) {
    let pieces: Vec<_> = traceparent.split('-').collect();
    if pieces.len() != 4 {
        return (None, None);
    }
    let trace_id = pieces[1];
    let parent_id = pieces[2];

    if !is_valid_trace_id(trace_id) || !is_valid_span_id(parent_id) {
        return (None, None);
    }

    (Some(trace_id.to_string()), Some(parent_id.to_string()))
227
228
}

229
#[derive(Debug, Clone, Default)]
230
231
232
233
234
pub struct TraceParent {
    pub trace_id: Option<String>,
    pub parent_id: Option<String>,
    pub tracestate: Option<String>,
    pub x_request_id: Option<String>,
235
    pub request_id: Option<String>,
236
237
}

238
239
240
241
242
243
244
245
246
pub trait GenericHeaders {
    fn get(&self, key: &str) -> Option<&str>;
}

impl GenericHeaders for async_nats::HeaderMap {
    fn get(&self, key: &str) -> Option<&str> {
        async_nats::HeaderMap::get(self, key).map(|value| value.as_str())
    }
}
247

248
249
250
251
252
253
254
255
impl GenericHeaders for http::HeaderMap {
    fn get(&self, key: &str) -> Option<&str> {
        http::HeaderMap::get(self, key).and_then(|value| value.to_str().ok())
    }
}

impl TraceParent {
    pub fn from_headers<H: GenericHeaders>(headers: &H) -> TraceParent {
256
257
258
        let mut trace_id = None;
        let mut parent_id = None;
        let mut tracestate = None;
259
        let mut x_request_id = None;
260
        let mut request_id = None;
261
262
263

        if let Some(header_value) = headers.get("traceparent") {
            (trace_id, parent_id) = parse_traceparent(header_value);
264
265
        }

266
267
        if let Some(header_value) = headers.get("x-request-id") {
            x_request_id = Some(header_value.to_string());
268
269
        }

270
271
272
273
        if let Some(header_value) = headers.get("tracestate") {
            tracestate = Some(header_value.to_string());
        }

274
275
276
277
278
        // Read request-id from internal headers, with fallback to deprecated x-dynamo-request-id
        if let Some(header_value) = headers.get("request-id") {
            request_id = Some(header_value.to_string());
        } else if let Some(header_value) = headers.get("x-dynamo-request-id") {
            request_id = Some(header_value.to_string());
279
        }
280

281
        let request_id = request_id.filter(|id| uuid::Uuid::parse_str(id).is_ok());
282
        TraceParent {
283
284
285
286
            trace_id,
            parent_id,
            tracestate,
            x_request_id,
287
            request_id,
288
        }
289
290
291
    }
}

292
293
294
295
296
297
/// Create a span for inference request endpoints (completions, chat, embeddings, etc.).
///
/// Uses `target: "request_span"` which is always allowed through the DYN_LOG filter
/// (via `request_span=trace` directive in `filters()`). This ensures request context
/// (request_id, model, trace_id) is always available on log events.
pub fn make_inference_request_span<B>(req: &Request<B>) -> Span {
298
299
300
301
302
    let method = req.method();
    let uri = req.uri();
    let version = format!("{:?}", req.version());
    let trace_parent = TraceParent::from_headers(req.headers());

303
304
    let otel_context = extract_otel_context_from_http_headers(req.headers());

305
306
307
308
309
    // Ensure every inference request has a request_id on the span.
    // This is the single source of truth — workers and get_or_create_request_id
    // read it back via DistributedTraceIdLayer.
    let request_id = trace_parent
        .request_id
310
311
        .unwrap_or_else(|| Uuid::new_v4().to_string());

312
    let span = tracing::info_span!(
313
            target: "request_span",
314
315
316
317
318
319
320
        "http-request",
        method = %method,
        uri = %uri,
        version = %version,
        trace_id = trace_parent.trace_id,
        parent_id = trace_parent.parent_id,
        x_request_id = trace_parent.x_request_id,
321
        request_id = %request_id,
322
323
324
        model = tracing::field::Empty,
        input_tokens = tracing::field::Empty,
        output_tokens = tracing::field::Empty,
325
326
327
328
        ttft_ms = tracing::field::Empty,
        avg_itl_ms = tracing::field::Empty,
        prefill_worker_id = tracing::field::Empty,
        decode_worker_id = tracing::field::Empty,
329
330
    );

331
332
333
334
    if let Some(context) = otel_context {
        let _ = span.set_parent(context);
    }

335
336
337
    span
}

338
/// Create a span for system endpoints (health, metrics, models, engine, loras, etc.).
339
///
340
341
342
343
/// Same structure as `make_inference_request_span` but uses `target: "system_span"`
/// which follows normal DYN_LOG filtering (debug level by default). The inference
/// span target `request_span` is always-on via a `request_span=trace` directive;
/// system spans are not, keeping high-frequency polling endpoints quiet.
344
345
346
pub fn make_system_request_span<B>(req: &Request<B>) -> Span {
    let method = req.method();
    let uri = req.uri();
347
348
349
350
351
352
353
354
355
356
    let version = format!("{:?}", req.version());
    let trace_parent = TraceParent::from_headers(req.headers());
    let otel_context = extract_otel_context_from_http_headers(req.headers());

    // Ensure every system request has a request_id on the span.
    let request_id = trace_parent
        .request_id
        .unwrap_or_else(|| Uuid::new_v4().to_string());

    let span = tracing::debug_span!(
357
358
359
360
        target: "system_span",
        "http-request",
        method = %method,
        uri = %uri,
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
        version = %version,
        trace_id = trace_parent.trace_id,
        parent_id = trace_parent.parent_id,
        x_request_id = trace_parent.x_request_id,
        request_id = %request_id,
        model = tracing::field::Empty,
        input_tokens = tracing::field::Empty,
        output_tokens = tracing::field::Empty,
        ttft_ms = tracing::field::Empty,
        avg_itl_ms = tracing::field::Empty,
        prefill_worker_id = tracing::field::Empty,
        decode_worker_id = tracing::field::Empty,
    );

    if let Some(context) = otel_context {
        let _ = span.set_parent(context);
    }

    span
380
381
}

382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/// Extract OpenTelemetry context from HTTP headers for distributed tracing
fn extract_otel_context_from_http_headers(
    headers: &http::HeaderMap,
) -> Option<opentelemetry::Context> {
    let traceparent_value = headers.get("traceparent")?.to_str().ok()?;

    struct HttpHeaderExtractor<'a>(&'a http::HeaderMap);

    impl<'a> Extractor for HttpHeaderExtractor<'a> {
        fn get(&self, key: &str) -> Option<&str> {
            self.0.get(key).and_then(|v| v.to_str().ok())
        }

        fn keys(&self) -> Vec<&str> {
            vec!["traceparent", "tracestate"]
                .into_iter()
                .filter(|&key| self.0.get(key).is_some())
                .collect()
        }
    }

    // Early return if traceparent is empty
    if traceparent_value.is_empty() {
        return None;
    }

    let extractor = HttpHeaderExtractor(headers);
    let otel_context = TRACE_PROPAGATOR.extract(&extractor);

    if otel_context.span().span_context().is_valid() {
        Some(otel_context)
    } else {
        None
    }
}

418
419
420
421
422
423
/// Create a handle_payload span from NATS headers with component context
pub fn make_handle_payload_span(
    headers: &async_nats::HeaderMap,
    component: &str,
    endpoint: &str,
    namespace: &str,
424
    instance_id: u64,
425
426
427
428
429
430
) -> Span {
    let (otel_context, trace_id, parent_span_id) = extract_otel_context_from_nats_headers(headers);
    let trace_parent = TraceParent::from_headers(headers);

    if let (Some(trace_id), Some(parent_id)) = (trace_id.as_ref(), parent_span_id.as_ref()) {
        let span = tracing::info_span!(
431
            target: "request_span",
432
433
434
435
            "handle_payload",
            trace_id = trace_id.as_str(),
            parent_id = parent_id.as_str(),
            x_request_id = trace_parent.x_request_id,
436
            request_id = trace_parent.request_id,
437
438
439
440
441
442
            tracestate = trace_parent.tracestate,
            component = component,
            endpoint = endpoint,
            namespace = namespace,
            instance_id = instance_id,
        );
443

444
445
446
447
448
449
        if let Some(context) = otel_context {
            let _ = span.set_parent(context);
        }
        span
    } else {
        tracing::info_span!(
450
            target: "request_span",
451
452
            "handle_payload",
            x_request_id = trace_parent.x_request_id,
453
            request_id = trace_parent.request_id,
454
455
456
457
458
459
460
461
462
            tracestate = trace_parent.tracestate,
            component = component,
            endpoint = endpoint,
            namespace = namespace,
            instance_id = instance_id,
        )
    }
}

463
464
465
466
467
468
469
470
471
472
/// Create a handle_payload span from TCP/HashMap headers with component context
pub fn make_handle_payload_span_from_tcp_headers(
    headers: &std::collections::HashMap<String, String>,
    component: &str,
    endpoint: &str,
    namespace: &str,
    instance_id: u64,
) -> Span {
    let (otel_context, trace_id, parent_span_id) = extract_otel_context_from_tcp_headers(headers);
    let x_request_id = headers.get("x-request-id").cloned();
473
474
475
476
477
    let request_id = headers
        .get("request-id")
        .or_else(|| headers.get("x-dynamo-request-id"))
        .filter(|id| uuid::Uuid::parse_str(id).is_ok())
        .cloned();
478
479
480
481
    let tracestate = headers.get("tracestate").cloned();

    if let (Some(trace_id), Some(parent_id)) = (trace_id.as_ref(), parent_span_id.as_ref()) {
        let span = tracing::info_span!(
482
            target: "request_span",
483
484
485
486
            "handle_payload",
            trace_id = trace_id.as_str(),
            parent_id = parent_id.as_str(),
            x_request_id = x_request_id,
487
            request_id = request_id,
488
489
490
491
492
493
494
495
496
497
498
499
500
            tracestate = tracestate,
            component = component,
            endpoint = endpoint,
            namespace = namespace,
            instance_id = instance_id,
        );

        if let Some(context) = otel_context {
            let _ = span.set_parent(context);
        }
        span
    } else {
        tracing::info_span!(
501
            target: "request_span",
502
503
            "handle_payload",
            x_request_id = x_request_id,
504
            request_id = request_id,
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
            tracestate = tracestate,
            component = component,
            endpoint = endpoint,
            namespace = namespace,
            instance_id = instance_id,
        )
    }
}

/// Extract OpenTelemetry trace context from TCP/HashMap headers for distributed tracing
fn extract_otel_context_from_tcp_headers(
    headers: &std::collections::HashMap<String, String>,
) -> (
    Option<opentelemetry::Context>,
    Option<String>,
    Option<String>,
) {
    let traceparent_value = match headers.get("traceparent") {
        Some(value) => value.as_str(),
        None => return (None, None, None),
    };

    let (trace_id, parent_span_id) = parse_traceparent(traceparent_value);

    struct TcpHeaderExtractor<'a>(&'a std::collections::HashMap<String, String>);

    impl<'a> Extractor for TcpHeaderExtractor<'a> {
        fn get(&self, key: &str) -> Option<&str> {
            self.0.get(key).map(|s| s.as_str())
        }

        fn keys(&self) -> Vec<&str> {
            vec!["traceparent", "tracestate"]
                .into_iter()
                .filter(|&key| self.0.get(key).is_some())
                .collect()
        }
    }

    let extractor = TcpHeaderExtractor(headers);
    let otel_context = TRACE_PROPAGATOR.extract(&extractor);

    let context_with_trace = if otel_context.span().span_context().is_valid() {
        Some(otel_context)
    } else {
        None
    };

    (context_with_trace, trace_id, parent_span_id)
}

556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
/// Extract OpenTelemetry trace context from NATS headers for distributed tracing
pub fn extract_otel_context_from_nats_headers(
    headers: &async_nats::HeaderMap,
) -> (
    Option<opentelemetry::Context>,
    Option<String>,
    Option<String>,
) {
    let traceparent_value = match headers.get("traceparent") {
        Some(value) => value.as_str(),
        None => return (None, None, None),
    };

    let (trace_id, parent_span_id) = parse_traceparent(traceparent_value);

    struct NatsHeaderExtractor<'a>(&'a async_nats::HeaderMap);

    impl<'a> Extractor for NatsHeaderExtractor<'a> {
        fn get(&self, key: &str) -> Option<&str> {
            self.0.get(key).map(|value| value.as_str())
        }

        fn keys(&self) -> Vec<&str> {
            vec!["traceparent", "tracestate"]
                .into_iter()
                .filter(|&key| self.0.get(key).is_some())
                .collect()
        }
    }

    let extractor = NatsHeaderExtractor(headers);
587
    let otel_context = TRACE_PROPAGATOR.extract(&extractor);
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613

    let context_with_trace = if otel_context.span().span_context().is_valid() {
        Some(otel_context)
    } else {
        None
    };

    (context_with_trace, trace_id, parent_span_id)
}

/// Inject OpenTelemetry trace context into NATS headers using W3C Trace Context propagation
pub fn inject_otel_context_into_nats_headers(
    headers: &mut async_nats::HeaderMap,
    context: Option<opentelemetry::Context>,
) {
    let otel_context = context.unwrap_or_else(|| Span::current().context());

    struct NatsHeaderInjector<'a>(&'a mut async_nats::HeaderMap);

    impl<'a> Injector for NatsHeaderInjector<'a> {
        fn set(&mut self, key: &str, value: String) {
            self.0.insert(key, value);
        }
    }

    let mut injector = NatsHeaderInjector(headers);
614
    TRACE_PROPAGATOR.inject_context(&otel_context, &mut injector);
615
616
617
618
619
620
621
}

/// Inject trace context from current span into NATS headers
pub fn inject_current_trace_into_nats_headers(headers: &mut async_nats::HeaderMap) {
    inject_otel_context_into_nats_headers(headers, None);
}

622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// Inject trace headers into a generic HashMap for HTTP/TCP transports
pub fn inject_trace_headers_into_map(headers: &mut std::collections::HashMap<String, String>) {
    if let Some(trace_context) = get_distributed_tracing_context() {
        // Inject W3C traceparent header
        headers.insert(
            "traceparent".to_string(),
            trace_context.create_traceparent(),
        );

        // Inject optional tracestate
        if let Some(tracestate) = trace_context.tracestate {
            headers.insert("tracestate".to_string(), tracestate);
        }

        // Inject custom request IDs
        if let Some(x_request_id) = trace_context.x_request_id {
            headers.insert("x-request-id".to_string(), x_request_id);
        }
640
641
        if let Some(request_id) = trace_context.request_id {
            headers.insert("request-id".to_string(), request_id);
642
643
644
645
        }
    }
}

646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
/// Create a client_request span linked to the parent trace context
pub fn make_client_request_span(
    operation: &str,
    request_id: &str,
    trace_context: Option<&DistributedTraceContext>,
    instance_id: Option<&str>,
) -> Span {
    if let Some(ctx) = trace_context {
        let mut headers = async_nats::HeaderMap::new();
        headers.insert("traceparent", ctx.create_traceparent());

        if let Some(ref tracestate) = ctx.tracestate {
            headers.insert("tracestate", tracestate.as_str());
        }

        let (otel_context, _extracted_trace_id, _extracted_parent_span_id) =
            extract_otel_context_from_nats_headers(&headers);

        let span = if let Some(inst_id) = instance_id {
            tracing::info_span!(
                "client_request",
                operation = operation,
                request_id = request_id,
                instance_id = inst_id,
                trace_id = ctx.trace_id.as_str(),
                parent_id = ctx.span_id.as_str(),
                x_request_id = ctx.x_request_id.as_deref(),
            )
        } else {
            tracing::info_span!(
                "client_request",
                operation = operation,
                request_id = request_id,
                trace_id = ctx.trace_id.as_str(),
                parent_id = ctx.span_id.as_str(),
                x_request_id = ctx.x_request_id.as_deref(),
            )
        };

        if let Some(context) = otel_context {
            let _ = span.set_parent(context);
        }

        span
    } else if let Some(inst_id) = instance_id {
        tracing::info_span!(
            "client_request",
            operation = operation,
            request_id = request_id,
            instance_id = inst_id,
        )
    } else {
        tracing::info_span!(
            "client_request",
            operation = operation,
            request_id = request_id,
        )
    }
704
705
}

706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
#[derive(Debug, Default)]
pub struct FieldVisitor {
    pub fields: HashMap<String, String>,
}

impl Visit for FieldVisitor {
    fn record_str(&mut self, field: &Field, value: &str) {
        self.fields
            .insert(field.name().to_string(), value.to_string());
    }

    fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
        self.fields
            .insert(field.name().to_string(), format!("{:?}", value).to_string());
    }
}

impl<S> Layer<S> for DistributedTraceIdLayer
where
    S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
{
    // Capture close span time
    // Currently not used but added for future use in timing
    fn on_close(&self, id: Id, ctx: Context<'_, S>) {
        if let Some(span) = ctx.span(&id) {
            let mut extensions = span.extensions_mut();
            if let Some(distributed_tracing_context) =
                extensions.get_mut::<DistributedTraceContext>()
            {
                distributed_tracing_context.end = Some(Instant::now());
            }
        }
    }

740
741
    // Collects span attributes and metadata in on_new_span
    // Final initialization deferred to on_enter when OtelData is available
742
743
744
745
746
747
    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
        if let Some(span) = ctx.span(id) {
            let mut trace_id: Option<String> = None;
            let mut parent_id: Option<String> = None;
            let mut span_id: Option<String> = None;
            let mut x_request_id: Option<String> = None;
748
            let mut request_id: Option<String> = None;
749
750
751
752
            let mut tracestate: Option<String> = None;
            let mut visitor = FieldVisitor::default();
            attrs.record(&mut visitor);

753
            // Extract trace_id from span attributes
754
755
            if let Some(trace_id_input) = visitor.fields.get("trace_id") {
                if !is_valid_trace_id(trace_id_input) {
756
                    tracing::trace!("trace id  '{trace_id_input}' is not valid! Ignoring.");
757
758
759
760
761
                } else {
                    trace_id = Some(trace_id_input.to_string());
                }
            }

762
            // Extract span_id from span attributes
763
764
            if let Some(span_id_input) = visitor.fields.get("span_id") {
                if !is_valid_span_id(span_id_input) {
765
                    tracing::trace!("span id  '{span_id_input}' is not valid! Ignoring.");
766
767
768
769
770
                } else {
                    span_id = Some(span_id_input.to_string());
                }
            }

771
            // Extract parent_id from span attributes
772
773
            if let Some(parent_id_input) = visitor.fields.get("parent_id") {
                if !is_valid_span_id(parent_id_input) {
774
                    tracing::trace!("parent id  '{parent_id_input}' is not valid! Ignoring.");
775
776
777
778
779
                } else {
                    parent_id = Some(parent_id_input.to_string());
                }
            }

780
            // Extract tracestate
781
782
783
784
            if let Some(tracestate_input) = visitor.fields.get("tracestate") {
                tracestate = Some(tracestate_input.to_string());
            }

785
            // Extract x_request_id
786
787
788
789
            if let Some(x_request_id_input) = visitor.fields.get("x_request_id") {
                x_request_id = Some(x_request_id_input.to_string());
            }

790
791
792
793
794
            // Extract request_id (with backward compat for x_dynamo_request_id)
            if let Some(request_id_input) = visitor.fields.get("request_id") {
                request_id = Some(request_id_input.to_string());
            } else if let Some(x_request_id_input) = visitor.fields.get("x_dynamo_request_id") {
                request_id = Some(x_request_id_input.to_string());
795
796
            }

797
            // Inherit trace context from parent span if available
798
799
800
801
802
803
804
805
806
            if parent_id.is_none()
                && let Some(parent_span_id) = ctx.current_span().id()
                && let Some(parent_span) = ctx.span(parent_span_id)
            {
                let parent_ext = parent_span.extensions();
                if let Some(parent_tracing_context) = parent_ext.get::<DistributedTraceContext>() {
                    trace_id = Some(parent_tracing_context.trace_id.clone());
                    parent_id = Some(parent_tracing_context.span_id.clone());
                    tracestate = parent_tracing_context.tracestate.clone();
807
808
809
810
811
812
                    if x_request_id.is_none() {
                        x_request_id = parent_tracing_context.x_request_id.clone();
                    }
                    if request_id.is_none() {
                        request_id = parent_tracing_context.request_id.clone();
                    }
813
814
815
                }
            }

816
            // Validate consistency
817
818
819
820
821
822
823
            if (parent_id.is_some() || span_id.is_some()) && trace_id.is_none() {
                tracing::error!("parent id or span id are set but trace id is not set!");
                // Clear inconsistent IDs to maintain trace integrity
                parent_id = None;
                span_id = None;
            }

824
825
826
827
828
829
830
831
            // Store pending context - will be finalized in on_enter
            let mut extensions = span.extensions_mut();
            extensions.insert(PendingDistributedTraceContext {
                trace_id,
                span_id,
                parent_id,
                tracestate,
                x_request_id,
832
                request_id,
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
            });
        }
    }

    // Finalizes the DistributedTraceContext when span is entered
    // At this point, OtelData should have valid trace_id and span_id
    fn on_enter(&self, id: &Id, ctx: Context<'_, S>) {
        if let Some(span) = ctx.span(id) {
            // Check if already initialized (e.g., span re-entered)
            {
                let extensions = span.extensions();
                if extensions.get::<DistributedTraceContext>().is_some() {
                    return;
                }
            }

            // Get the pending context and extract OtelData IDs
            let mut extensions = span.extensions_mut();
            let pending = match extensions.remove::<PendingDistributedTraceContext>() {
                Some(p) => p,
                None => {
                    // This shouldn't happen - on_new_span should have created it
                    tracing::error!("PendingDistributedTraceContext not found in on_enter");
                    return;
                }
            };

            let mut trace_id = pending.trace_id;
            let mut span_id = pending.span_id;
            let parent_id = pending.parent_id;
            let tracestate = pending.tracestate;
            let x_request_id = pending.x_request_id;
865
            let request_id = pending.request_id;
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896

            // Try to extract from OtelData if not already set
            // Need to drop extensions_mut to get immutable borrow for OtelData
            drop(extensions);

            if trace_id.is_none() || span_id.is_none() {
                let extensions = span.extensions();
                if let Some(otel_data) = extensions.get::<tracing_opentelemetry::OtelData>() {
                    // Extract trace_id from OTEL data if not already set
                    if trace_id.is_none()
                        && let Some(otel_trace_id) = otel_data.trace_id()
                    {
                        let trace_id_str = format!("{}", otel_trace_id);
                        if is_valid_trace_id(&trace_id_str) {
                            trace_id = Some(trace_id_str);
                        }
                    }

                    // Extract span_id from OTEL data if not already set
                    if span_id.is_none()
                        && let Some(otel_span_id) = otel_data.span_id()
                    {
                        let span_id_str = format!("{}", otel_span_id);
                        if is_valid_span_id(&span_id_str) {
                            span_id = Some(span_id_str);
                        }
                    }
                }
            }

            // Panic if we still don't have required IDs
897
            if trace_id.is_none() {
898
899
900
                panic!(
                    "trace_id is not set in on_enter - OtelData may not be properly initialized"
                );
901
            }
902

903
            if span_id.is_none() {
904
                panic!("span_id is not set in on_enter - OtelData may not be properly initialized");
905
906
            }

907
            let span_level = span.metadata().level();
908
909
910
911
912
913
            let mut extensions = span.extensions_mut();
            extensions.insert(DistributedTraceContext {
                trace_id: trace_id.expect("Trace ID must be set"),
                span_id: span_id.expect("Span ID must be set"),
                parent_id,
                tracestate,
914
                start: Some(Instant::now()),
915
916
                end: None,
                x_request_id,
917
                request_id,
918
            });
919
920
921
922
923
924
925
926

            drop(extensions);

            // Emit SPAN_FIRST_ENTRY event. This only runs if the span passed the layer's filter
            // (on_enter is not called for filtered-out spans), so no additional check needed.
            if span_events_enabled() {
                emit_at_level!(span_level, target: "span_event", message = "SPAN_FIRST_ENTRY");
            }
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
        }
    }
}

// Enables functions to retreive their current
// context for adding to distributed headers
pub fn get_distributed_tracing_context() -> Option<DistributedTraceContext> {
    Span::current()
        .with_subscriber(|(id, subscriber)| {
            subscriber
                .downcast_ref::<Registry>()
                .and_then(|registry| registry.span_data(id))
                .and_then(|span_data| {
                    let extensions = span_data.extensions();
                    extensions.get::<DistributedTraceContext>().cloned()
                })
        })
        .flatten()
}

947
/// Initialize the logger - must be called when Tokio runtime is available
948
pub fn init() {
949
950
951
952
953
954
    INIT.call_once(|| {
        if let Err(e) = setup_logging() {
            eprintln!("Failed to initialize logging: {}", e);
            std::process::exit(1);
        }
    });
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
}

#[cfg(feature = "tokio-console")]
fn setup_logging() {
    let tokio_console_layer = console_subscriber::ConsoleLayer::builder()
        .with_default_env()
        .server_addr(([0, 0, 0, 0], console_subscriber::Server::DEFAULT_PORT))
        .spawn();
    let tokio_console_target = tracing_subscriber::filter::Targets::new()
        .with_default(LevelFilter::ERROR)
        .with_target("runtime", LevelFilter::TRACE)
        .with_target("tokio", LevelFilter::TRACE);
    let l = fmt::layer()
        .with_ansi(!disable_ansi_logging())
        .event_format(fmt::format().compact().with_timer(TimeFormatter::new()))
        .with_writer(std::io::stderr)
971
        .with_filter(filters(load_config()));
972
973
974
975
976
977
978
    tracing_subscriber::registry()
        .with(l)
        .with(tokio_console_layer.with_filter(tokio_console_target))
        .init();
}

#[cfg(not(feature = "tokio-console"))]
979
fn setup_logging() -> Result<(), Box<dyn std::error::Error>> {
980
981
    let fmt_filter_layer = filters(load_config());
    let trace_filter_layer = filters(load_config());
982
    let otel_filter_layer = filters(load_config());
983
    let otel_logs_filter_layer = filters(load_config());
984

985
    if jsonl_logging_enabled() {
986
987
988
989
990
        let span_events = if span_events_enabled() {
            FmtSpan::CLOSE
        } else {
            FmtSpan::NONE
        };
991
992
        let l = fmt::layer()
            .with_ansi(false)
993
            .with_span_events(span_events)
994
995
            .event_format(CustomJsonFormatter::new())
            .with_writer(std::io::stderr)
996
            .with_filter(fmt_filter_layer);
997
998
999
1000

        // Create OpenTelemetry tracer - conditionally export to OTLP based on env var
        let service_name = get_service_name();

1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
        // Build tracer and logger providers - with or without OTLP export
        let (tracer_provider, logger_provider_opt, endpoint_opt) = if otlp_exporter_enabled() {
            // Export enabled: create OTLP exporters with batch processors
            let traces_endpoint =
                std::env::var(env_logging::otlp::OTEL_EXPORTER_OTLP_TRACES_ENDPOINT)
                    .unwrap_or_else(|_| DEFAULT_OTLP_ENDPOINT.to_string());
            let logs_endpoint = std::env::var(env_logging::otlp::OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)
                .unwrap_or_else(|_| traces_endpoint.clone());

            let resource = opentelemetry_sdk::Resource::builder_empty()
                .with_service_name(service_name.clone())
                .build();
1013

1014
1015
            // Initialize OTLP span exporter using gRPC (Tonic)
            let span_exporter = opentelemetry_otlp::SpanExporter::builder()
1016
                .with_tonic()
1017
                .with_endpoint(&traces_endpoint)
1018
1019
                .build()?;

1020
1021
1022
            let tracer_provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
                .with_batch_exporter(span_exporter)
                .with_resource(resource.clone())
1023
1024
                .build();

1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
            // Initialize OTLP log exporter using gRPC (Tonic)
            let log_exporter = opentelemetry_otlp::LogExporter::builder()
                .with_tonic()
                .with_endpoint(&logs_endpoint)
                .build()?;

            let logger_provider = SdkLoggerProvider::builder()
                .with_batch_exporter(log_exporter)
                .with_resource(resource)
                .build();

            (
                tracer_provider,
                Some(logger_provider),
                Some(traces_endpoint),
            )
1041
1042
        } else {
            // No export - traces generated locally only (for logging/trace IDs)
1043
            let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
1044
1045
1046
1047
1048
                .with_resource(
                    opentelemetry_sdk::Resource::builder_empty()
                        .with_service_name(service_name.clone())
                        .build(),
                )
1049
1050
                .build();

1051
            (provider, None, None)
1052
1053
1054
        };

        // Get a tracer from the provider
1055
        let tracer = tracer_provider.tracer(service_name.clone());
1056

1057
1058
1059
1060
1061
        // Build the OTLP logs bridge layer (only when export is enabled)
        let otel_logs_layer = logger_provider_opt
            .as_ref()
            .map(|lp| OpenTelemetryTracingBridge::new(lp).with_filter(otel_logs_filter_layer));

1062
        tracing_subscriber::registry()
1063
1064
1065
1066
1067
            .with(
                tracing_opentelemetry::layer()
                    .with_tracer(tracer)
                    .with_filter(otel_filter_layer),
            )
1068
            .with(otel_logs_layer)
1069
            .with(DistributedTraceIdLayer.with_filter(trace_filter_layer))
1070
1071
            .with(l)
            .init();
1072
1073
1074
1075
1076
1077

        // Log initialization status after subscriber is ready
        if let Some(endpoint) = endpoint_opt {
            tracing::info!(
                endpoint = %endpoint,
                service = %service_name,
1078
                "OpenTelemetry OTLP export enabled (traces and logs)"
1079
1080
1081
1082
1083
1084
1085
            );
        } else {
            tracing::info!(
                service = %service_name,
                "OpenTelemetry OTLP export disabled, traces local only"
            );
        }
1086
1087
1088
1089
1090
    } else {
        let l = fmt::layer()
            .with_ansi(!disable_ansi_logging())
            .event_format(fmt::format().compact().with_timer(TimeFormatter::new()))
            .with_writer(std::io::stderr)
1091
            .with_filter(fmt_filter_layer);
1092

1093
1094
        tracing_subscriber::registry().with(l).init();
    }
1095
1096

    Ok(())
1097
1098
1099
1100
1101
}

fn filters(config: LoggingConfig) -> EnvFilter {
    let mut filter_layer = EnvFilter::builder()
        .with_default_directive(config.log_level.parse().unwrap())
1102
        .with_env_var(env_logging::DYN_LOG)
1103
1104
1105
1106
1107
1108
1109
1110
1111
        .from_env_lossy();

    for (module, level) in config.log_filters {
        match format!("{module}={level}").parse::<Directive>() {
            Ok(d) => {
                filter_layer = filter_layer.add_directive(d);
            }
            Err(e) => {
                eprintln!("Failed parsing filter '{level}' for module '{module}': {e}");
1112
1113
            }
        }
1114
    }
1115
1116
1117
1118
1119
1120
1121

    // When span events are enabled, allow "span_event" target at all levels
    // This ensures SPAN_FIRST_ENTRY events pass the filter when emitted from on_enter
    if span_events_enabled() {
        filter_layer = filter_layer.add_directive("span_event=trace".parse().unwrap());
    }

1122
1123
1124
1125
1126
1127
    // Always allow infrastructure request spans regardless of DYN_LOG level.
    // This ensures request context (request_id, model, trace_id) is always
    // available on log events, even when DYN_LOG=error or DYN_LOG=warn.
    // Can be overridden via DYN_LOG=request_span=<level> if needed.
    filter_layer = filter_layer.add_directive("request_span=trace".parse().unwrap());

1128
    filter_layer
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
}

/// Log a message with file and line info
/// Used by Python wrapper
pub fn log_message(level: &str, message: &str, module: &str, file: &str, line: u32) {
    let level = match level {
        "debug" => log::Level::Debug,
        "info" => log::Level::Info,
        "warn" => log::Level::Warn,
        "error" => log::Level::Error,
        "warning" => log::Level::Warn,
        _ => log::Level::Info,
    };
    log::logger().log(
        &log::Record::builder()
            .args(format_args!("{}", message))
            .level(level)
            .target(module)
            .file(Some(file))
            .line(Some(line))
            .build(),
    );
}

fn load_config() -> LoggingConfig {
1154
1155
    let config_path =
        std::env::var(env_logging::DYN_LOGGING_CONFIG_PATH).unwrap_or_else(|_| "".to_string());
1156
1157
    let figment = Figment::new()
        .merge(Serialized::defaults(LoggingConfig::default()))
Neelay Shah's avatar
Neelay Shah committed
1158
        .merge(Toml::file("/opt/dynamo/etc/logging.toml"))
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
        .merge(Toml::file(config_path));

    figment.extract().unwrap()
}

#[derive(Serialize)]
struct JsonLog<'a> {
    time: String,
    level: String,
    #[serde(skip_serializing_if = "Option::is_none")]
1169
    file: Option<&'a str>,
1170
    #[serde(skip_serializing_if = "Option::is_none")]
1171
    line: Option<u32>,
1172
    target: String,
1173
1174
1175
1176
1177
    message: serde_json::Value,
    #[serde(flatten)]
    fields: BTreeMap<String, serde_json::Value>,
}

Ryan Olson's avatar
Ryan Olson committed
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
struct TimeFormatter {
    use_local_tz: bool,
}

impl TimeFormatter {
    fn new() -> Self {
        Self {
            use_local_tz: crate::config::use_local_timezone(),
        }
    }

    fn format_now(&self) -> String {
        if self.use_local_tz {
            chrono::Local::now()
1192
                .format("%Y-%m-%dT%H:%M:%S%.6f%:z")
Ryan Olson's avatar
Ryan Olson committed
1193
1194
1195
                .to_string()
        } else {
            chrono::Utc::now()
1196
                .format("%Y-%m-%dT%H:%M:%S%.6fZ")
Ryan Olson's avatar
Ryan Olson committed
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
                .to_string()
        }
    }
}

impl FormatTime for TimeFormatter {
    fn format_time(&self, w: &mut fmt::format::Writer<'_>) -> std::fmt::Result {
        write!(w, "{}", self.format_now())
    }
}

struct CustomJsonFormatter {
    time_formatter: TimeFormatter,
}

impl CustomJsonFormatter {
    fn new() -> Self {
        Self {
            time_formatter: TimeFormatter::new(),
        }
    }
}
1219

1220
1221
use once_cell::sync::Lazy;
use regex::Regex;
1222
1223
1224
1225
1226

/// Static W3C Trace Context propagator instance to avoid repeated allocations
static TRACE_PROPAGATOR: Lazy<opentelemetry_sdk::propagation::TraceContextPropagator> =
    Lazy::new(opentelemetry_sdk::propagation::TraceContextPropagator::new);

1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
fn parse_tracing_duration(s: &str) -> Option<u64> {
    static RE: Lazy<Regex> =
        Lazy::new(|| Regex::new(r#"^["']?\s*([0-9.]+)\s*(µs|us|ns|ms|s)\s*["']?$"#).unwrap());
    let captures = RE.captures(s)?;
    let value: f64 = captures[1].parse().ok()?;
    let unit = &captures[2];
    match unit {
        "ns" => Some((value / 1000.0) as u64),
        "µs" | "us" => Some(value as u64),
        "ms" => Some((value * 1000.0) as u64),
        "s" => Some((value * 1_000_000.0) as u64),
        _ => None,
    }
}

1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
impl<S, N> tracing_subscriber::fmt::FormatEvent<S, N> for CustomJsonFormatter
where
    S: Subscriber + for<'a> LookupSpan<'a>,
    N: for<'a> FormatFields<'a> + 'static,
{
    fn format_event(
        &self,
        ctx: &FmtContext<'_, S, N>,
        mut writer: Writer<'_>,
        event: &Event<'_>,
    ) -> std::fmt::Result {
        let mut visitor = JsonVisitor::default();
1254
        let time = self.time_formatter.format_now();
1255
        event.record(&mut visitor);
1256
        let mut message = visitor
1257
1258
1259
1260
            .fields
            .remove("message")
            .unwrap_or(serde_json::Value::String("".to_string()));

1261
1262
        let mut target_override: Option<String> = None;

1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
        let current_span = event
            .parent()
            .and_then(|id| ctx.span(id))
            .or_else(|| ctx.lookup_current());
        if let Some(span) = current_span {
            let ext = span.extensions();
            let data = ext.get::<FormattedFields<N>>().unwrap();
            let span_fields: Vec<(&str, &str)> = data
                .fields
                .split(' ')
                .filter_map(|entry| entry.split_once('='))
                .collect();
            for (name, value) in span_fields {
                visitor.fields.insert(
                    name.to_string(),
                    serde_json::Value::String(value.trim_matches('"').to_string()),
                );
            }
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305

            let busy_us = visitor
                .fields
                .remove("time.busy")
                .and_then(|v| parse_tracing_duration(&v.to_string()));
            let idle_us = visitor
                .fields
                .remove("time.idle")
                .and_then(|v| parse_tracing_duration(&v.to_string()));

            if let (Some(busy_us), Some(idle_us)) = (busy_us, idle_us) {
                visitor.fields.insert(
                    "time.busy_us".to_string(),
                    serde_json::Value::Number(busy_us.into()),
                );
                visitor.fields.insert(
                    "time.idle_us".to_string(),
                    serde_json::Value::Number(idle_us.into()),
                );
                visitor.fields.insert(
                    "time.duration_us".to_string(),
                    serde_json::Value::Number((busy_us + idle_us).into()),
                );
            }

1306
1307
1308
1309
1310
1311
1312
1313
            let is_span_created = message.as_str() == Some("SPAN_FIRST_ENTRY");
            let is_span_closed = message.as_str() == Some("close");
            if is_span_created || is_span_closed {
                target_override = Some(span.metadata().target().to_string());
                if is_span_closed {
                    message = serde_json::Value::String("SPAN_CLOSED".to_string());
                }
            }
1314

1315
1316
1317
1318
1319
            visitor.fields.insert(
                "span_name".to_string(),
                serde_json::Value::String(span.name().to_string()),
            );

1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
            if let Some(tracing_context) = ext.get::<DistributedTraceContext>() {
                visitor.fields.insert(
                    "span_id".to_string(),
                    serde_json::Value::String(tracing_context.span_id.clone()),
                );
                visitor.fields.insert(
                    "trace_id".to_string(),
                    serde_json::Value::String(tracing_context.trace_id.clone()),
                );
                if let Some(parent_id) = tracing_context.parent_id.clone() {
                    visitor.fields.insert(
                        "parent_id".to_string(),
                        serde_json::Value::String(parent_id),
                    );
                } else {
                    visitor.fields.remove("parent_id");
                }
                if let Some(tracestate) = tracing_context.tracestate.clone() {
                    visitor.fields.insert(
                        "tracestate".to_string(),
                        serde_json::Value::String(tracestate),
                    );
                } else {
                    visitor.fields.remove("tracestate");
                }
                if let Some(x_request_id) = tracing_context.x_request_id.clone() {
                    visitor.fields.insert(
                        "x_request_id".to_string(),
                        serde_json::Value::String(x_request_id),
                    );
                } else {
                    visitor.fields.remove("x_request_id");
                }
1353

1354
                if let Some(request_id) = tracing_context.request_id.clone() {
1355
                    visitor.fields.insert(
1356
1357
                        "request_id".to_string(),
                        serde_json::Value::String(request_id),
1358
1359
                    );
                } else {
1360
                    visitor.fields.remove("request_id");
1361
                }
1362
1363
                // Remove old field name if present
                visitor.fields.remove("x_dynamo_request_id");
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
            } else {
                tracing::error!(
                    "Distributed Trace Context not found, falling back to internal ids"
                );
                visitor.fields.insert(
                    "span_id".to_string(),
                    serde_json::Value::String(span.id().into_u64().to_string()),
                );
                if let Some(parent) = span.parent() {
                    visitor.fields.insert(
                        "parent_id".to_string(),
                        serde_json::Value::String(parent.id().into_u64().to_string()),
                    );
                }
            }
        } else {
            let reserved_fields = [
                "trace_id",
                "span_id",
                "parent_id",
                "span_name",
                "tracestate",
            ];
            for reserved_field in reserved_fields {
                visitor.fields.remove(reserved_field);
            }
        }
1391
1392
1393
        let metadata = event.metadata();
        let log = JsonLog {
            level: metadata.level().to_string(),
1394
1395
1396
            time,
            file: metadata.file(),
            line: metadata.line(),
1397
            target: target_override.unwrap_or_else(|| metadata.target().to_string()),
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
            message,
            fields: visitor.fields,
        };
        let json = serde_json::to_string(&log).unwrap();
        writeln!(writer, "{json}")
    }
}

#[derive(Default)]
struct JsonVisitor {
    fields: BTreeMap<String, serde_json::Value>,
}

impl tracing::field::Visit for JsonVisitor {
    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
        self.fields.insert(
            field.name().to_string(),
            serde_json::Value::String(format!("{value:?}")),
        );
    }

    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
1420
1421
1422
1423
1424
1425
1426
1427
        if field.name() != "message" {
            match serde_json::from_str::<Value>(value) {
                Ok(json_val) => self.fields.insert(field.name().to_string(), json_val),
                Err(_) => self.fields.insert(field.name().to_string(), value.into()),
            };
        } else {
            self.fields.insert(field.name().to_string(), value.into());
        }
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
    }

    fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
        self.fields
            .insert(field.name().to_string(), serde_json::Value::Bool(value));
    }

    fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
        self.fields.insert(
            field.name().to_string(),
            serde_json::Value::Number(value.into()),
        );
    }

    fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
        self.fields.insert(
            field.name().to_string(),
            serde_json::Value::Number(value.into()),
        );
    }

    fn record_f64(&mut self, field: &tracing::field::Field, value: f64) {
        use serde_json::value::Number;
        self.fields.insert(
            field.name().to_string(),
            serde_json::Value::Number(Number::from_f64(value).unwrap_or(0.into())),
        );
    }
}
1457
1458
1459
1460

#[cfg(test)]
pub mod tests {
    use super::*;
1461
    use anyhow::{Result, anyhow};
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
    use chrono::{DateTime, Utc};
    use jsonschema::{Draft, JSONSchema};
    use serde_json::Value;
    use std::fs::File;
    use std::io::{BufRead, BufReader};
    use stdio_override::*;
    use tempfile::NamedTempFile;

    static LOG_LINE_SCHEMA: &str = r#"
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "Runtime Log Line",
      "type": "object",
      "required": [
        "file",
        "level",
        "line",
        "message",
        "target",
        "time"
      ],
      "properties": {
        "file":      { "type": "string" },
        "level":     { "type": "string", "enum": ["ERROR", "WARN", "INFO", "DEBUG", "TRACE"] },
        "line":      { "type": "integer" },
        "message":   { "type": "string" },
        "target":    { "type": "string" },
        "time":      { "type": "string", "format": "date-time" },
        "span_id":   { "type": "string", "pattern": "^[a-f0-9]{16}$" },
        "parent_id": { "type": "string", "pattern": "^[a-f0-9]{16}$" },
        "trace_id":  { "type": "string", "pattern": "^[a-f0-9]{32}$" },
        "span_name": { "type": "string" },
        "time.busy_us":     { "type": "integer" },
        "time.duration_us": { "type": "integer" },
        "time.idle_us":     { "type": "integer" },
        "tracestate": { "type": "string" }
      },
      "additionalProperties": true
    }
    "#;

1503
    #[tracing::instrument(skip_all)]
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
    async fn parent() {
        tracing::trace!(message = "parent!");
        if let Some(my_ctx) = get_distributed_tracing_context() {
            tracing::info!(my_trace_id = my_ctx.trace_id);
        }
        child().await;
    }

    #[tracing::instrument(skip_all)]
    async fn child() {
        tracing::trace!(message = "child");
        if let Some(my_ctx) = get_distributed_tracing_context() {
            tracing::info!(my_trace_id = my_ctx.trace_id);
        }
        grandchild().await;
    }

    #[tracing::instrument(skip_all)]
    async fn grandchild() {
        tracing::trace!(message = "grandchild");
        if let Some(my_ctx) = get_distributed_tracing_context() {
            tracing::info!(my_trace_id = my_ctx.trace_id);
        }
    }

    pub fn load_log(file_name: &str) -> Result<Vec<serde_json::Value>> {
        let schema_json: Value =
            serde_json::from_str(LOG_LINE_SCHEMA).expect("schema parse failure");
        let compiled_schema = JSONSchema::options()
            .with_draft(Draft::Draft7)
            .compile(&schema_json)
            .expect("Invalid schema");

        let f = File::open(file_name)?;
        let reader = BufReader::new(f);
        let mut result = Vec::new();

        for (line_num, line) in reader.lines().enumerate() {
            let line = line?;
            let val: Value = serde_json::from_str(&line)
                .map_err(|e| anyhow!("Line {}: invalid JSON: {}", line_num + 1, e))?;

            if let Err(errors) = compiled_schema.validate(&val) {
                let errs = errors.map(|e| e.to_string()).collect::<Vec<_>>().join("; ");
                return Err(anyhow!(
                    "Line {}: JSON Schema Validation errors: {}",
                    line_num + 1,
                    errs
                ));
            }
            println!("{}", val);
            result.push(val);
        }
        Ok(result)
    }

    #[tokio::test]
    async fn test_json_log_capture() -> Result<()> {
        #[allow(clippy::redundant_closure_call)]
        let _ = temp_env::async_with_vars(
1564
            [(env_logging::DYN_LOGGING_JSONL, Some("1"))],
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
            (async || {
                let tmp_file = NamedTempFile::new().unwrap();
                let file_name = tmp_file.path().to_str().unwrap();
                let guard = StderrOverride::from_file(file_name)?;
                init();
                parent().await;
                drop(guard);

                let lines = load_log(file_name)?;

1575
1576
                // 1. Extract the dynamically generated trace ID and validate consistency
                // All logs should have the same trace_id since they're part of the same trace
1577
                // Skip any initialization logs that don't have trace_id (e.g., OTLP setup messages)
1578
1579
1580
1581
1582
                //
                // Note: This test can fail if logging was already initialized by another test running
                // in parallel. Logging initialization is global (Once) and can only happen once per process.
                // If no trace_id is found, skip validation gracefully.
                let Some(trace_id) = lines
1583
1584
                    .iter()
                    .find_map(|log_line| log_line.get("trace_id").and_then(|v| v.as_str()))
1585
1586
1587
1588
1589
                    .map(|s| s.to_string())
                else {
                    // Skip test if logging was already initialized - we can't control the output format
                    return Ok(());
                };
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612

                // Verify trace_id is not a zero/invalid ID
                assert_ne!(
                    trace_id, "00000000000000000000000000000000",
                    "trace_id should not be a zero/invalid ID"
                );
                assert!(
                    !trace_id.chars().all(|c| c == '0'),
                    "trace_id should not be all zeros"
                );

                // Verify all logs have the same trace_id
                for log_line in &lines {
                    if let Some(line_trace_id) = log_line.get("trace_id") {
                        assert_eq!(
                            line_trace_id.as_str().unwrap(),
                            &trace_id,
                            "All logs should have the same trace_id"
                        );
                    }
                }

                // Validate my_trace_id matches the actual trace ID
1613
1614
1615
1616
                for log_line in &lines {
                    if let Some(my_trace_id) = log_line.get("my_trace_id") {
                        assert_eq!(
                            my_trace_id,
1617
1618
                            &serde_json::Value::String(trace_id.clone()),
                            "my_trace_id should match the trace_id from distributed tracing context"
1619
1620
1621
1622
                        );
                    }
                }

1623
1624
1625
                // 2. Validate span IDs exist and are properly formatted
                let mut span_ids_seen: std::collections::HashSet<String> = std::collections::HashSet::new();
                let mut span_timestamps: std::collections::HashMap<String, DateTime<Utc>> = std::collections::HashMap::new();
1626
1627

                for log_line in &lines {
1628
1629
1630
1631
1632
1633
1634
1635
                    if let Some(span_id) = log_line.get("span_id") {
                        let span_id_str = span_id.as_str().unwrap();
                        assert!(
                            is_valid_span_id(span_id_str),
                            "Invalid span_id format: {}",
                            span_id_str
                        );
                        span_ids_seen.insert(span_id_str.to_string());
1636
1637
                    }

1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
                    // Validate timestamp format and track span timestamps
                    if let Some(time_str) = log_line.get("time").and_then(|v| v.as_str()) {
                        let timestamp = DateTime::parse_from_rfc3339(time_str)
                            .expect("All timestamps should be valid RFC3339 format")
                            .with_timezone(&Utc);

                        // Track timestamp for each span_name
                        if let Some(span_name) = log_line.get("span_name").and_then(|v| v.as_str()) {
                            span_timestamps.insert(span_name.to_string(), timestamp);
                        }
                    }
1649
1650
                }

1651
1652
                // 3. Validate parent-child span relationships
                // Extract span IDs for each span by looking at their log messages
1653
1654
1655
                let parent_span_id = lines
                    .iter()
                    .find(|log_line| {
1656
1657
                        log_line.get("span_name")
                            .and_then(|v| v.as_str()) == Some("parent")
1658
1659
                    })
                    .and_then(|log_line| {
1660
1661
1662
                        log_line.get("span_id")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string())
1663
                    })
1664
                    .expect("Should find parent span with span_id");
1665
1666
1667
1668

                let child_span_id = lines
                    .iter()
                    .find(|log_line| {
1669
1670
                        log_line.get("span_name")
                            .and_then(|v| v.as_str()) == Some("child")
1671
1672
                    })
                    .and_then(|log_line| {
1673
1674
1675
                        log_line.get("span_id")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string())
1676
                    })
1677
                    .expect("Should find child span with span_id");
1678

1679
                let grandchild_span_id = lines
1680
1681
                    .iter()
                    .find(|log_line| {
1682
1683
                        log_line.get("span_name")
                            .and_then(|v| v.as_str()) == Some("grandchild")
1684
1685
                    })
                    .and_then(|log_line| {
1686
1687
1688
                        log_line.get("span_id")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string())
1689
                    })
1690
1691
1692
1693
1694
1695
                    .expect("Should find grandchild span with span_id");

                // Verify span IDs are unique
                assert_ne!(parent_span_id, child_span_id, "Parent and child should have different span IDs");
                assert_ne!(child_span_id, grandchild_span_id, "Child and grandchild should have different span IDs");
                assert_ne!(parent_span_id, grandchild_span_id, "Parent and grandchild should have different span IDs");
1696

1697
                // Verify parent span has no parent_id
1698
                for log_line in &lines {
1699
1700
1701
1702
                    if let Some(span_name) = log_line.get("span_name")
                        && let Some(span_name_str) = span_name.as_str()
                        && span_name_str == "parent"
                    {
1703
1704
1705
1706
                        assert!(
                            log_line.get("parent_id").is_none(),
                            "Parent span should not have a parent_id"
                        );
1707
1708
1709
                    }
                }

1710
                // Verify child span's parent_id is parent_span_id
1711
                for log_line in &lines {
1712
1713
1714
1715
                    if let Some(span_name) = log_line.get("span_name")
                        && let Some(span_name_str) = span_name.as_str()
                        && span_name_str == "child"
                    {
1716
1717
1718
                        let parent_id = log_line.get("parent_id")
                            .and_then(|v| v.as_str())
                            .expect("Child span should have a parent_id");
1719
                        assert_eq!(
1720
1721
1722
                            parent_id,
                            parent_span_id,
                            "Child's parent_id should match parent's span_id"
1723
                        );
1724
1725
1726
                    }
                }

1727
                // Verify grandchild span's parent_id is child_span_id
1728
                for log_line in &lines {
1729
1730
1731
1732
                    if let Some(span_name) = log_line.get("span_name")
                        && let Some(span_name_str) = span_name.as_str()
                        && span_name_str == "grandchild"
                    {
1733
1734
1735
                        let parent_id = log_line.get("parent_id")
                            .and_then(|v| v.as_str())
                            .expect("Grandchild span should have a parent_id");
1736
                        assert_eq!(
1737
1738
1739
                            parent_id,
                            child_span_id,
                            "Grandchild's parent_id should match child's span_id"
1740
                        );
1741
1742
1743
                    }
                }

1744
1745
1746
1747
1748
1749
1750
                // 4. Validate timestamp ordering - spans should log in execution order
                let parent_time = span_timestamps.get("parent")
                    .expect("Should have timestamp for parent span");
                let child_time = span_timestamps.get("child")
                    .expect("Should have timestamp for child span");
                let grandchild_time = span_timestamps.get("grandchild")
                    .expect("Should have timestamp for grandchild span");
1751

1752
                // Parent logs first (or at same time), then child, then grandchild
1753
                assert!(
1754
1755
1756
1757
                    parent_time <= child_time,
                    "Parent span should log before or at same time as child span (parent: {}, child: {})",
                    parent_time,
                    child_time
1758
1759
                );
                assert!(
1760
1761
1762
1763
                    child_time <= grandchild_time,
                    "Child span should log before or at same time as grandchild span (child: {}, grandchild: {})",
                    child_time,
                    grandchild_time
1764
1765
1766
1767
1768
1769
1770
1771
                );

                Ok::<(), anyhow::Error>(())
            })(),
        )
        .await;
        Ok(())
    }
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995

    // Test functions at different log levels for filtering tests
    #[tracing::instrument(level = "debug", skip_all)]
    async fn debug_level_span() {
        tracing::debug!("inside debug span");
    }

    #[tracing::instrument(level = "info", skip_all)]
    async fn info_level_span() {
        tracing::info!("inside info span");
    }

    #[tracing::instrument(level = "warn", skip_all)]
    async fn warn_level_span() {
        tracing::warn!("inside warn span");
    }

    // Span from a different target - should be FILTERED OUT at info level
    // because the filter is warn,dynamo_runtime::logging::tests=debug
    #[tracing::instrument(level = "info", target = "other_module", skip_all)]
    async fn other_target_info_span() {
        tracing::info!(target: "other_module", "inside other target span");
    }

    /// Comprehensive test for span events covering:
    /// - SPAN_FIRST_ENTRY and SPAN_CLOSED event emission
    /// - Trace context (trace_id, span_id) in span events
    /// - Timing information in SPAN_CLOSED events
    /// - Level-based filtering (positive: allowed levels pass, negative: filtered levels blocked)
    /// - Target-based filtering (spans from allowed targets pass even at lower levels)
    ///
    /// This test runs in a subprocess to ensure logging is initialized with our specific
    /// filter settings (DYN_LOG=warn,dynamo_runtime::logging::tests=debug), avoiding
    /// interference from other tests that may have initialized logging first.
    #[test]
    fn test_span_events() {
        use std::process::Command;

        // Run cargo test for the subprocess test with specific env vars
        let output = Command::new("cargo")
            .args([
                "test",
                "-p",
                "dynamo-runtime",
                "test_span_events_subprocess",
                "--",
                "--exact",
                "--nocapture",
            ])
            .env("DYN_LOGGING_JSONL", "1")
            .env("DYN_LOGGING_SPAN_EVENTS", "1")
            .env("DYN_LOG", "warn,dynamo_runtime::logging::tests=debug")
            .output()
            .expect("Failed to execute subprocess test");

        // Print output for debugging
        if !output.status.success() {
            eprintln!(
                "=== STDOUT ===\n{}",
                String::from_utf8_lossy(&output.stdout)
            );
            eprintln!(
                "=== STDERR ===\n{}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        assert!(
            output.status.success(),
            "Subprocess test failed with exit code: {:?}",
            output.status.code()
        );
    }

    /// Subprocess test that performs the actual span event validation.
    /// This is called by test_span_events in a separate process with controlled env vars.
    #[tokio::test]
    async fn test_span_events_subprocess() -> Result<()> {
        // Skip if not running as subprocess (env vars not set)
        if std::env::var("DYN_LOGGING_SPAN_EVENTS").is_err() {
            return Ok(());
        }

        let tmp_file = NamedTempFile::new().unwrap();
        let file_name = tmp_file.path().to_str().unwrap();
        let guard = StderrOverride::from_file(file_name)?;
        init();

        // Run parent/child/grandchild spans (all INFO level by default)
        parent().await;

        // Run spans at explicit levels from our test module
        debug_level_span().await;
        info_level_span().await;
        warn_level_span().await;

        // Run span from different target (should be filtered out)
        other_target_info_span().await;

        drop(guard);

        let lines = load_log(file_name)?;

        // Helper to check if a span event exists
        let has_span_event = |msg: &str, span_name: &str| {
            lines.iter().any(|log| {
                log.get("message").and_then(|v| v.as_str()) == Some(msg)
                    && log.get("span_name").and_then(|v| v.as_str()) == Some(span_name)
            })
        };

        // Helper to get span events
        let get_span_events = |msg: &str| -> Vec<&serde_json::Value> {
            lines
                .iter()
                .filter(|log| log.get("message").and_then(|v| v.as_str()) == Some(msg))
                .collect()
        };

        // === Test 1: SPAN_FIRST_ENTRY events have required fields ===
        let span_created_events = get_span_events("SPAN_FIRST_ENTRY");
        for event in &span_created_events {
            // Must have span_name
            assert!(
                event.get("span_name").is_some(),
                "SPAN_FIRST_ENTRY must have span_name"
            );
            // Must have valid trace_id (format check)
            let trace_id = event
                .get("trace_id")
                .and_then(|v| v.as_str())
                .expect("SPAN_FIRST_ENTRY must have trace_id");
            assert!(
                trace_id.len() == 32 && trace_id.chars().all(|c| c.is_ascii_hexdigit()),
                "SPAN_FIRST_ENTRY must have valid trace_id format"
            );
            // Must have valid span_id
            let span_id = event
                .get("span_id")
                .and_then(|v| v.as_str())
                .expect("SPAN_FIRST_ENTRY must have span_id");
            assert!(
                is_valid_span_id(span_id),
                "SPAN_FIRST_ENTRY must have valid span_id"
            );
        }

        // === Test 2: SPAN_CLOSED events have timing info ===
        let span_closed_events = get_span_events("SPAN_CLOSED");
        for event in &span_closed_events {
            assert!(
                event.get("span_name").is_some(),
                "SPAN_CLOSED must have span_name"
            );
            assert!(
                event.get("time.busy_us").is_some()
                    || event.get("time.idle_us").is_some()
                    || event.get("time.duration_us").is_some(),
                "SPAN_CLOSED must have timing information"
            );
            // Must have valid trace_id
            let trace_id = event
                .get("trace_id")
                .and_then(|v| v.as_str())
                .expect("SPAN_CLOSED must have trace_id");
            assert!(
                trace_id.len() == 32 && trace_id.chars().all(|c| c.is_ascii_hexdigit()),
                "SPAN_CLOSED must have valid trace_id format"
            );
        }

        // === Test 3: Target-based filtering (positive) ===
        // Spans from dynamo_runtime::logging::tests should pass at ALL levels
        // because the target is allowed at debug level
        assert!(
            has_span_event("SPAN_FIRST_ENTRY", "debug_level_span"),
            "DEBUG span from allowed target MUST pass (target=debug filter)"
        );
        assert!(
            has_span_event("SPAN_FIRST_ENTRY", "info_level_span"),
            "INFO span from allowed target MUST pass (target=debug filter)"
        );
        assert!(
            has_span_event("SPAN_FIRST_ENTRY", "warn_level_span"),
            "WARN span from allowed target MUST pass (target=debug filter)"
        );

        // parent/child/grandchild are INFO level from allowed target - should pass
        assert!(
            has_span_event("SPAN_FIRST_ENTRY", "parent"),
            "parent span (INFO) from allowed target MUST pass"
        );
        assert!(
            has_span_event("SPAN_FIRST_ENTRY", "child"),
            "child span (INFO) from allowed target MUST pass"
        );
        assert!(
            has_span_event("SPAN_FIRST_ENTRY", "grandchild"),
            "grandchild span (INFO) from allowed target MUST pass"
        );

        // === Test 4: Level-based filtering (negative) ===
        // Verify spans from OTHER targets at debug/info level are filtered out
        assert!(
            !has_span_event("SPAN_FIRST_ENTRY", "other_target_info_span"),
            "INFO span from non-allowed target (other_module) MUST be filtered out"
        );

        // Also verify no spans from other targets appear at debug/info level
        for event in &span_created_events {
            let target = event.get("target").and_then(|v| v.as_str()).unwrap_or("");
            let level = event.get("level").and_then(|v| v.as_str()).unwrap_or("");

            // If level is DEBUG or INFO, target must be our test module
            if level == "DEBUG" || level == "INFO" {
                assert!(
                    target.contains("dynamo_runtime::logging::tests"),
                    "DEBUG/INFO span must be from allowed target, got target={target}"
                );
            }
        }

        Ok(())
    }
1996
}