|
| 1 | +use std::{ |
| 2 | + fmt::Write, |
| 3 | + sync::{ |
| 4 | + atomic::{AtomicU64, Ordering}, |
| 5 | + Arc, |
| 6 | + }, |
| 7 | +}; |
| 8 | + |
| 9 | +use tracing::{span, Level}; |
| 10 | +use tracing_subscriber::{layer::SubscriberExt, Registry}; |
| 11 | + |
| 12 | +use tracing_tree::{time::FormatTime, HierarchicalLayer}; |
| 13 | + |
| 14 | +#[derive(Debug)] |
| 15 | +struct FormatTimeCounter(Arc<AtomicU64>); |
| 16 | + |
| 17 | +impl FormatTime for FormatTimeCounter { |
| 18 | + fn format_time(&self, _w: &mut impl Write) -> std::fmt::Result { |
| 19 | + self.0.fetch_add(1, Ordering::Relaxed); |
| 20 | + Ok(()) |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +#[test] |
| 25 | +fn format_time_num_calls() { |
| 26 | + let num_called = Arc::new(AtomicU64::new(0)); |
| 27 | + let format_time_counter = FormatTimeCounter(Arc::clone(&num_called)); |
| 28 | + |
| 29 | + let layer = HierarchicalLayer::default() |
| 30 | + .with_writer(std::io::stdout) |
| 31 | + .with_indent_lines(true) |
| 32 | + .with_indent_amount(2) |
| 33 | + .with_timer(format_time_counter) |
| 34 | + .with_thread_names(true) |
| 35 | + .with_thread_ids(true) |
| 36 | + .with_verbose_exit(true) |
| 37 | + .with_verbose_entry(true) |
| 38 | + .with_targets(true); |
| 39 | + |
| 40 | + let subscriber = Registry::default().with(layer); |
| 41 | + tracing::subscriber::set_global_default(subscriber).unwrap(); |
| 42 | + |
| 43 | + let test_span = span!(Level::TRACE, "format-time-num-calls-test", version = %0.1); |
| 44 | + let _e = test_span.enter(); |
| 45 | + |
| 46 | + tracing::info!("first event"); |
| 47 | + assert_eq!(num_called.load(Ordering::Relaxed), 1); |
| 48 | + |
| 49 | + std::thread::sleep(std::time::Duration::from_millis(100)); |
| 50 | + tracing::info!("second event"); |
| 51 | + assert_eq!(num_called.load(Ordering::Relaxed), 2); |
| 52 | + |
| 53 | + let nested_span = span!(Level::TRACE, "nested-span"); |
| 54 | + nested_span.in_scope(|| { |
| 55 | + tracing::debug!("nested event"); |
| 56 | + assert_eq!(num_called.load(Ordering::Relaxed), 3); |
| 57 | + |
| 58 | + tracing::info!("important nested event"); |
| 59 | + assert_eq!(num_called.load(Ordering::Relaxed), 4); |
| 60 | + }); |
| 61 | + drop(nested_span); |
| 62 | + |
| 63 | + instrumented_function(); |
| 64 | + assert_eq!(num_called.load(Ordering::Relaxed), 6); |
| 65 | + |
| 66 | + tracing::info!("exiting"); |
| 67 | + assert_eq!(num_called.load(Ordering::Relaxed), 7); |
| 68 | +} |
| 69 | + |
| 70 | +#[tracing::instrument] |
| 71 | +fn instrumented_function() { |
| 72 | + tracing::info!("instrumented function"); |
| 73 | + nested_instrumented_function(); |
| 74 | +} |
| 75 | + |
| 76 | +#[tracing::instrument] |
| 77 | +fn nested_instrumented_function() { |
| 78 | + tracing::warn!("nested instrumented function"); |
| 79 | +} |
0 commit comments