doc_sync_layered/
doc_sync_layered.rs

1//! Demonstrates how to use [`LatencyTrace`] as a [`Layer`](tracing_subscriber::layer::Layer)
2//! that can be composed with other layers to make a layered [`Subscriber`](tracing::Subscriber).
3//!
4//! Compare with examples `doc_sync` and `doc_sync_fmt` in the GitHub repo.
5
6use latency_trace::{summary_stats, LatencyTrace};
7use std::{thread, time::Duration};
8use tracing::{info, instrument, level_filters::LevelFilter, trace, trace_span};
9use tracing_subscriber::{fmt::format::FmtSpan, prelude::*, Registry};
10
11#[instrument(level = "info")]
12fn f() {
13    trace!("in f");
14    for _ in 0..10 {
15        trace_span!("loop_body").in_scope(|| {
16            info!("in loop body");
17            // Simulated work
18            thread::sleep(Duration::from_micros(1200));
19
20            g();
21        });
22    }
23}
24
25#[instrument(level = "info")]
26fn g() {
27    trace!("in g");
28    // Simulated work
29    thread::sleep(Duration::from_micros(800));
30}
31
32fn main() {
33    // LatencyTrace instance from which latency statistics will be extracted later.
34    let lt = LatencyTrace::default();
35
36    // Clone of the above that will be used as a `tracing_subscriber::layer::Layer` that can be
37    // composed with other tracing layers. Add a filter so that only spans with level `INFO` or
38    // higher priority (lower level) are aggregated.
39    let ltl = lt.clone().with_filter(LevelFilter::INFO);
40
41    // `tracing_subscriber::fmt::Layer` that can be composed with the above `LatencyTrace` layer.
42    // Spans with level `TRACE` or higher priority (lower level) are displayed.
43    let tfmt = tracing_subscriber::fmt::layer()
44        .with_span_events(FmtSpan::FULL)
45        .with_filter(LevelFilter::TRACE);
46
47    // Instantiate a layered subscriber and set it as the global default.
48    let layered = Registry::default().with(ltl).with(tfmt);
49    layered.init();
50
51    // Measure latencies.
52    let latencies = lt.measure_latencies(f);
53
54    println!("\nLatency stats below are in microseconds");
55    for (span_group, stats) in latencies.map_values(summary_stats) {
56        println!("  * {:?}, {:?}", span_group, stats);
57    }
58
59    // A shorter way to print the summary stats, with uglier formatting.
60    println!("\nDebug print of `latencies.map_values(summary_stats)`:");
61    println!("{:?}", latencies.map_values(summary_stats));
62}