logfire 0.9.0

Rust SDK for Pydantic Logfire
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
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
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
587
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
use std::{
    io::{self, BufWriter, IsTerminal, Write},
    sync::{Arc, Mutex, mpsc},
};

use chrono::{DateTime, Utc};
use nu_ansi_term::{Color, Style};
use opentelemetry::{Value, logs::AnyValue};
use opentelemetry_sdk::logs::SdkLogRecord;
use opentelemetry_sdk::trace::SpanData;

use crate::{
    bridges::tracing::tracing_level_to_severity,
    config::{ConsoleOptions, Target},
    internal::{constants::ATTRIBUTES_SPAN_TYPE_KEY, span_data_ext::SpanDataExt},
};

/// Enum to represent different types of telemetry data that can be written to console
#[derive(Debug)]
enum ConsoleItem {
    Span(SpanData),
    Log(SdkLogRecord),
}

/// Shared state for console processors
#[derive(Debug)]
struct ConsoleSharedState {
    tx: mpsc::Sender<ConsoleItem>,
    thread_handle: std::thread::JoinHandle<()>,
}

impl ConsoleSharedState {
    fn shutdown_with_timeout(
        self,
        timeout: std::time::Duration,
    ) -> opentelemetry_sdk::error::OTelSdkResult {
        // Close the channel to signal shutdown
        drop(self.tx);
        // Wait for the thread to finish, polling every 10ms
        let start = std::time::Instant::now();
        loop {
            if self.thread_handle.is_finished() {
                self.thread_handle.join().expect("failed to join thread");
                break;
            }
            if start.elapsed() >= timeout {
                return Err(opentelemetry_sdk::error::OTelSdkError::Timeout(timeout));
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        Ok(())
    }
}

/// Create both console processors that share a single background thread
pub fn create_console_processors(
    writer: Arc<ConsoleWriter>,
) -> (SimpleConsoleSpanProcessor, SimpleConsoleLogProcessor) {
    let (tx, rx) = mpsc::channel();

    // Spawn a single thread to handle both spans and logs
    let thread_handle = std::thread::spawn(move || {
        while let Ok(item) = rx.recv() {
            match item {
                ConsoleItem::Span(span) => writer.write_batch(&[span]),
                ConsoleItem::Log(log_record) => writer.write_log_batch(&[log_record]),
            }
        }
    });

    let shared_state = Arc::new(ConsoleSharedState { tx, thread_handle });

    let span_processor = SimpleConsoleSpanProcessor {
        shared_state: Mutex::new(Some(shared_state.clone())),
    };

    let log_processor = SimpleConsoleLogProcessor {
        shared_state: Mutex::new(Some(shared_state)),
    };

    (span_processor, log_processor)
}

/// Simple span processor which sends spans to the shared console writer.
#[derive(Debug)]
pub struct SimpleConsoleSpanProcessor {
    shared_state: Mutex<Option<Arc<ConsoleSharedState>>>,
}

impl opentelemetry_sdk::trace::SpanProcessor for SimpleConsoleSpanProcessor {
    fn on_start(&self, _span: &mut opentelemetry_sdk::trace::Span, _cx: &opentelemetry::Context) {}

    fn on_end(&self, span: opentelemetry_sdk::trace::SpanData) {
        if let Some(state) = self.shared_state.lock().expect("no poisoning").as_mut() {
            state
                .tx
                .send(ConsoleItem::Span(span))
                .expect("failed to send span to console writer");
        }
    }

    fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult {
        Ok(())
    }

    fn shutdown_with_timeout(
        &self,
        timeout: std::time::Duration,
    ) -> opentelemetry_sdk::error::OTelSdkResult {
        if let Some(state) = self
            .shared_state
            .lock()
            .expect("no poisoning")
            .take()
            .and_then(Arc::into_inner)
        {
            state.shutdown_with_timeout(timeout)?;
        }
        Ok(())
    }
}

/// Simple log processor which sends logs to the shared console writer.
#[derive(Debug)]
pub struct SimpleConsoleLogProcessor {
    shared_state: Mutex<Option<Arc<ConsoleSharedState>>>,
}

impl opentelemetry_sdk::logs::LogProcessor for SimpleConsoleLogProcessor {
    fn emit(
        &self,
        log_record: &mut SdkLogRecord,
        _instrumentation_scope: &opentelemetry::InstrumentationScope,
    ) {
        if let Some(state) = self.shared_state.lock().expect("no poisoning").as_mut() {
            state
                .tx
                .send(ConsoleItem::Log(log_record.clone()))
                .expect("failed to send log to console writer");
        }
    }

    fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult {
        Ok(())
    }

    fn shutdown_with_timeout(
        &self,
        timeout: std::time::Duration,
    ) -> opentelemetry_sdk::error::OTelSdkResult {
        if let Some(state) = self
            .shared_state
            .lock()
            .expect("no poisoning")
            .take()
            .and_then(Arc::into_inner)
        {
            state.shutdown_with_timeout(timeout)?;
        }
        Ok(())
    }
}

/// Theme used to control console output, currently only a plain and "colored" theme.
struct Theme {
    dimmed: Style,
    dimmed_and_italic: Style,
    bold: Style,
    italic: Style,
    // log levels
    trace: Style,
    debug: Style,
    info: Style,
    warn: Style,
    error: Style,
    unknown: Style,
}

const BLANK_STYLE: Style = Style {
    foreground: None,
    background: None,
    is_bold: false,
    is_dimmed: false,
    is_italic: false,
    is_underline: false,
    is_blink: false,
    is_reverse: false,
    is_hidden: false,
    is_strikethrough: false,
    prefix_with_reset: false,
};

static THEME_COLORS: Theme = Theme {
    dimmed: BLANK_STYLE.dimmed(),
    dimmed_and_italic: BLANK_STYLE.dimmed().italic(),
    bold: BLANK_STYLE.bold(),
    italic: BLANK_STYLE.italic(),
    trace: BLANK_STYLE.fg(Color::Purple),
    debug: BLANK_STYLE.fg(Color::Blue),
    info: BLANK_STYLE.fg(Color::Green),
    warn: BLANK_STYLE.fg(Color::Yellow),
    error: BLANK_STYLE.fg(Color::Red),
    unknown: BLANK_STYLE.fg(Color::DarkGray),
};

static THEME_PLAIN: Theme = Theme {
    dimmed: BLANK_STYLE,
    dimmed_and_italic: BLANK_STYLE,
    bold: BLANK_STYLE,
    italic: BLANK_STYLE,
    // log levels
    trace: BLANK_STYLE,
    debug: BLANK_STYLE,
    info: BLANK_STYLE,
    warn: BLANK_STYLE,
    error: BLANK_STYLE,
    unknown: BLANK_STYLE,
};

fn level_int_to_text<W: io::Write>(level: i64, w: &mut W, theme: &Theme) -> io::Result<()> {
    match level {
        1 => write!(w, "{}", theme.trace.paint(" TRACE")),
        2..=5 => write!(w, "{}", theme.debug.paint(" DEBUG")),
        6..=9 => write!(w, "{}", theme.info.paint("  INFO")),
        10..=13 => write!(w, "{}", theme.warn.paint("  WARN")),
        14.. => write!(w, "{}", theme.error.paint(" ERROR")),
        _ => write!(w, "{}", theme.unknown.paint(" -----")),
    }
}

pub struct ConsoleWriter {
    options: ConsoleOptions,
    theme: &'static Theme,
}

impl ConsoleWriter {
    pub fn new(options: ConsoleOptions) -> Self {
        let use_colors = match options.colors {
            crate::config::ConsoleColors::Always => true,
            crate::config::ConsoleColors::Never => false,
            crate::config::ConsoleColors::Auto => match options.target {
                Target::Stdout => std::io::stdout().is_terminal(),
                Target::Stderr => std::io::stderr().is_terminal(),
                Target::Pipe(_) => false,
            },
        };
        let theme = if use_colors {
            &THEME_COLORS
        } else {
            &THEME_PLAIN
        };
        Self { options, theme }
    }

    pub fn write_batch(&self, batch: &[opentelemetry_sdk::trace::SpanData]) {
        self.with_writer(|w| {
            let mut buffer = BufWriter::new(w);
            for span in batch {
                let _ = self.span_to_writer(span, &mut buffer);
            }
        });
    }

    pub fn write_log_batch(&self, batch: &[SdkLogRecord]) {
        self.with_writer(|w| {
            let mut buffer = BufWriter::new(w);
            for log_data in batch {
                let _ = self.log_to_writer(log_data, &mut buffer);
            }
        });
    }

    fn with_writer<R>(&self, f: impl FnOnce(&mut dyn Write) -> R) -> R {
        match &self.options.target {
            Target::Stdout => f(&mut io::stdout().lock()),
            Target::Stderr => f(&mut io::stderr().lock()),
            Target::Pipe(p) => f(&mut *p.lock().expect("pipe lock poisoned")),
        }
    }

    fn span_to_writer<W: io::Write>(&self, span: &SpanData, w: &mut W) -> io::Result<()> {
        // only print for pending span and logs
        if span.get_span_type().is_none_or(|ty| ty == "span") {
            return Ok(());
        }

        let mut msg = None;
        let mut level = None;
        let mut target = None;

        let mut fields = Vec::new();

        for kv in &span.attributes {
            match kv.key.as_str() {
                "logfire.msg" => {
                    msg = Some(kv.value.as_str());
                }
                "logfire.level_num" => {
                    if let Value::I64(level_num) = kv.value {
                        #[expect(deprecated)]
                        if level_num < tracing_level_to_severity(self.options.min_log_level) as i64
                        {
                            return Ok(());
                        }
                        level = Some(level_num);
                    }
                }
                "code.namespace" => target = Some(kv.value.as_str()),
                // Filter out known values
                ATTRIBUTES_SPAN_TYPE_KEY
                | "logfire.json_schema"
                | "logfire.pending_parent_id"
                | "code.filepath"
                | "code.lineno"
                | "thread.id"
                | "thread.name"
                | "logfire.null_args"
                | "busy_ns"
                | "idle_ns" => (),
                _ => {
                    fields.push(kv);
                }
            }
        }

        if msg.is_none() {
            msg = Some(span.name.clone());
        }

        #[expect(deprecated)]
        if self.options.include_timestamps {
            let timestamp: DateTime<Utc> = span.start_time.into();
            write!(
                w,
                "{}",
                self.theme
                    .dimmed
                    .paint(timestamp.format("%Y-%m-%dT%H:%M:%S%.6fZ").to_string())
            )?;
        }

        if let Some(level) = level {
            level_int_to_text(level, w, self.theme)?;
        }

        if let Some(target) = target {
            write!(w, " {}", self.theme.dimmed_and_italic.paint(target))?;
        }

        if let Some(msg) = msg {
            write!(w, " {}", self.theme.bold.paint(msg))?;
        }

        if !fields.is_empty() {
            for (idx, kv) in fields.iter().enumerate() {
                let key = kv.key.as_str();
                let value = kv.value.as_str();
                write!(w, " {}={value}", self.theme.italic.paint(key))?;
                if idx < fields.len() - 1 {
                    write!(w, ",")?;
                }
            }
        }

        writeln!(w)
    }

    fn log_to_writer<W: io::Write>(&self, log_record: &SdkLogRecord, w: &mut W) -> io::Result<()> {
        let mut msg = None;
        let mut target = None;

        let mut fields = Vec::new();

        for (key, value) in log_record.attributes_iter() {
            match key.as_str() {
                "logfire.msg" => {
                    if let opentelemetry::logs::AnyValue::String(s) = value {
                        msg = Some(s.as_str());
                    }
                }
                "code.namespace" => {
                    if let opentelemetry::logs::AnyValue::String(s) = value {
                        target = Some(s.as_str());
                    }
                }
                // Filter out known values
                "logfire.json_schema"
                | "code.filepath"
                | "code.lineno"
                | "thread.id"
                | "thread.name"
                | "logfire.null_args"
                | "busy_ns"
                | "idle_ns" => (),
                _ => {
                    fields.push((key, value));
                }
            }
        }

        if msg.is_none() {
            // Use the body as the message if no logfire.msg
            if let Some(AnyValue::String(s)) = log_record.body() {
                msg = Some(s.as_str());
            }
        }

        #[expect(deprecated)]
        if self.options.include_timestamps {
            if let Some(timestamp) = log_record.timestamp() {
                let timestamp: DateTime<Utc> = timestamp.into();
                write!(
                    w,
                    "{}",
                    self.theme
                        .dimmed
                        .paint(timestamp.format("%Y-%m-%dT%H:%M:%S%.6fZ").to_string())
                )?;
            }
        }

        if let Some(level) = log_record.severity_number() {
            level_int_to_text(level as i64, w, self.theme)?;
        }

        if let Some(target) = target {
            write!(w, " {}", self.theme.dimmed_and_italic.paint(target))?;
        }

        if let Some(msg) = msg {
            write!(w, " {}", self.theme.bold.paint(msg))?;
        }

        if !fields.is_empty() {
            for (idx, (key, value)) in fields.iter().enumerate() {
                let key = key.as_str();

                write!(w, " {}=", self.theme.italic.paint(key))?;
                write_any_value(w, value, self.theme)?;

                if idx < fields.len() - 1 {
                    write!(w, ",")?;
                }
            }
        }

        writeln!(w)
    }
}

fn write_any_value<W: io::Write>(w: &mut W, value: &AnyValue, theme: &Theme) -> io::Result<()> {
    match value {
        AnyValue::Int(i) => {
            write!(w, "{i}")?;
        }
        AnyValue::Double(d) => {
            write!(w, "{d}")?;
        }
        AnyValue::String(s) => {
            write!(w, "{s}")?;
        }
        AnyValue::Boolean(b) => {
            write!(w, "{b}")?;
        }
        AnyValue::Bytes(items) => {
            write!(
                w,
                "{}",
                theme.dimmed.paint(format!("<bytes:{}>", items.len()))
            )?;
        }
        AnyValue::ListAny(list_values) => {
            for (idx, val) in list_values.iter().enumerate() {
                write_any_value(w, val, theme)?;

                if idx < list_values.len() - 1 {
                    write!(w, ",")?;
                }
            }
        }
        AnyValue::Map(hash_map) => {
            write!(w, "{{")?;

            for (idx, (key, val)) in (**hash_map).iter().enumerate() {
                write!(w, "{}=", theme.italic.paint(key.as_str()))?;
                write_any_value(w, val, theme)?;

                if idx < hash_map.len() - 1 {
                    write!(w, ",")?;
                }
            }
            write!(w, "}}")?;
        }
        other => {
            write!(w, "{other:?}")?;
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use crate::{
        config::{ConsoleColors, ConsoleOptions, Target},
        set_local_logfire,
        test_utils::remap_timestamps_in_console_output,
    };
    use insta::assert_snapshot;
    use tracing::{Level, level_filters::LevelFilter};

    #[test]
    fn test_print_to_console() {
        let output = Arc::new(Mutex::new(Vec::new()));

        let console_options = ConsoleOptions::default()
            .with_target(Target::Pipe(output.clone()))
            .with_min_log_level(Level::TRACE);

        let logfire = crate::configure()
            .local()
            .send_to_logfire(false)
            .with_console(Some(console_options))
            .with_default_level_filter(LevelFilter::TRACE)
            .finish()
            .unwrap();

        let guard = set_local_logfire(logfire);

        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let root = crate::span!("root span").entered();
            let _ = crate::span!("hello world span").entered();
            let _ = crate::span!(level: Level::DEBUG, "debug span");
            let _ =
                crate::span!(parent: &root, level: Level::DEBUG, "debug span with explicit parent");
            crate::info!("log with values", foo = 42, bar = 33);
            crate::info!("hello world log");
            panic!("oh no!");
        }))
        .unwrap_err();

        guard.shutdown().unwrap();

        let output = output.lock().unwrap();
        let output = std::str::from_utf8(&output).unwrap();
        let output = remap_timestamps_in_console_output(output);

        assert_snapshot!(output, @r"
        1970-01-01T00:00:00.000000Z  INFO logfire::internal::exporters::console::tests root span
        1970-01-01T00:00:00.000001Z  INFO logfire::internal::exporters::console::tests hello world span
        1970-01-01T00:00:00.000002Z DEBUG logfire::internal::exporters::console::tests debug span
        1970-01-01T00:00:00.000003Z DEBUG logfire::internal::exporters::console::tests debug span with explicit parent
        1970-01-01T00:00:00.000004Z  INFO logfire::internal::exporters::console::tests log with values foo=42, bar=33
        1970-01-01T00:00:00.000005Z  INFO logfire::internal::exporters::console::tests hello world log
        1970-01-01T00:00:00.000006Z ERROR panic: oh no! backtrace=disabled backtrace
        ");
    }

    #[test]
    fn test_print_to_console_force_colors() {
        let output = Arc::new(Mutex::new(Vec::new()));

        let console_options = ConsoleOptions::default()
            .with_colors(ConsoleColors::Always)
            .with_target(Target::Pipe(output.clone()))
            .with_min_log_level(Level::TRACE);

        let logfire = crate::configure()
            .local()
            .send_to_logfire(false)
            .with_console(Some(console_options))
            .with_default_level_filter(LevelFilter::TRACE)
            .finish()
            .unwrap();

        let guard = set_local_logfire(logfire);

        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let root = crate::span!("root span").entered();
            let _ = crate::span!("hello world span").entered();
            let _ = crate::span!(level: Level::DEBUG, "debug span");
            let _ =
                crate::span!(parent: &root, level: Level::DEBUG, "debug span with explicit parent");
            crate::info!("log with values", foo = 42, bar = 33);
            crate::info!("hello world log");
            panic!("oh no!");
        }))
        .unwrap_err();

        guard.shutdown().unwrap();

        let output = output.lock().unwrap();
        let output = std::str::from_utf8(&output).unwrap();
        let output = remap_timestamps_in_console_output(output);

        assert_snapshot!(output, @r"
        1970-01-01T00:00:00.000000Z  INFO logfire::internal::exporters::console::tests root span
        1970-01-01T00:00:00.000001Z  INFO logfire::internal::exporters::console::tests hello world span
        1970-01-01T00:00:00.000002Z DEBUG logfire::internal::exporters::console::tests debug span
        1970-01-01T00:00:00.000003Z DEBUG logfire::internal::exporters::console::tests debug span with explicit parent
        1970-01-01T00:00:00.000004Z  INFO logfire::internal::exporters::console::tests log with values foo=42, bar=33
        1970-01-01T00:00:00.000005Z  INFO logfire::internal::exporters::console::tests hello world log
        1970-01-01T00:00:00.000006Z ERROR panic: oh no! backtrace=disabled backtrace
        ");
    }

    #[test]
    fn test_print_to_console_include_timestamps_false() {
        let output = Arc::new(Mutex::new(Vec::new()));

        let console_options = ConsoleOptions::default()
            .with_target(Target::Pipe(output.clone()))
            .with_include_timestamps(false)
            .with_min_log_level(Level::TRACE);

        let logfire = crate::configure()
            .local()
            .send_to_logfire(false)
            .with_console(Some(console_options))
            .with_default_level_filter(LevelFilter::TRACE)
            .finish()
            .unwrap();

        let guard = set_local_logfire(logfire);

        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let root = crate::span!("root span").entered();
            let _ = crate::span!("hello world span").entered();
            let _ = crate::span!(level: Level::DEBUG, "debug span");
            let _ =
                crate::span!(parent: &root, level: Level::DEBUG, "debug span with explicit parent");
            crate::info!("hello world log");
            panic!("oh no!");
        }))
        .unwrap_err();

        guard.shutdown().unwrap();

        let output = output.lock().unwrap();
        let output = std::str::from_utf8(&output).unwrap();
        let output = remap_timestamps_in_console_output(output);

        assert_snapshot!(output, @r"
         INFO logfire::internal::exporters::console::tests root span
         INFO logfire::internal::exporters::console::tests hello world span
        DEBUG logfire::internal::exporters::console::tests debug span
        DEBUG logfire::internal::exporters::console::tests debug span with explicit parent
         INFO logfire::internal::exporters::console::tests hello world log
        ERROR panic: oh no! backtrace=disabled backtrace
        ");
    }

    #[test]
    fn test_print_to_console_with_min_log_level() {
        let output = Arc::new(Mutex::new(Vec::new()));

        let console_options = ConsoleOptions::default()
            .with_target(Target::Pipe(output.clone()))
            .with_min_log_level(Level::INFO);

        let logfire = crate::configure()
            .local()
            .send_to_logfire(false)
            .with_console(Some(console_options))
            .with_default_level_filter(LevelFilter::TRACE)
            .finish()
            .unwrap();

        let guard = set_local_logfire(logfire);

        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let root = crate::span!("root span").entered();
            let _ = crate::span!("hello world span").entered();
            let _ = crate::span!(level: Level::DEBUG, "debug span");
            let _ =
                crate::span!(parent: &root, level: Level::DEBUG, "debug span with explicit parent");
            crate::info!("hello world log");
            panic!("oh no!");
        }))
        .unwrap_err();

        guard.shutdown().unwrap();

        let output = output.lock().unwrap();
        let output = std::str::from_utf8(&output).unwrap();
        let output = remap_timestamps_in_console_output(output);

        assert_snapshot!(output, @r"
        1970-01-01T00:00:00.000000Z  INFO logfire::internal::exporters::console::tests root span
        1970-01-01T00:00:00.000001Z  INFO logfire::internal::exporters::console::tests hello world span
        1970-01-01T00:00:00.000002Z  INFO logfire::internal::exporters::console::tests hello world log
        1970-01-01T00:00:00.000003Z ERROR panic: oh no! backtrace=disabled backtrace
        ");
    }

    /// Regression test for https://github.com/pydantic/logfire-rust/issues/46
    #[test]
    fn test_console_deadlock() {
        let shutdown_handler = crate::configure()
            .send_to_logfire(false)
            .local()
            .finish()
            .unwrap();

        let guard = set_local_logfire(shutdown_handler.clone());

        // Why did this deadlock?
        //
        // - calling `crate::info!` would use `SimpleSpanProcessor` to record the span
        // - `SimpleSpanProcessor` had a mutex, which it locked, and then used `block_on` internally to call the exporter
        // - `block_on` would panic, which caused another span to be emitted
        // - this then deadlocked inside `SimpleSpanProcessor` because it was already holding the mutex
        futures::executor::block_on(async {
            crate::info!("Testing console output with tokio sleep");
        });

        drop(guard);

        shutdown_handler.shutdown().ok();
    }
}