Skip to main content

gix_trace/forest/
mod.rs

1//! Collect related tracing spans and events into trees, then process each completed root.
2//!
3//! [`ForestLayer`](crate::ForestLayer) works with a [`tracing_subscriber::Registry`]. Its default processor
4//! pretty-prints trees to stdout; [`processor::from_fn`] can instead collect or forward
5//! them, and [`Printer`] combines a [`Formatter`] with a writer. Processing is synchronous
6//! on the thread that closes a root span or emits an event without a parent.
7//!
8//! Install only one `ForestLayer` per registry: its per-span state occupies one shared
9//! extension slot, regardless of the layer's processor and tag types. For multiple
10//! output destinations, collect once and send the completed trees to the desired
11//! formatting or storage sinks.
12//!
13//! This module ports the synchronous core of
14//! [`tracing-forest` 0.2.0](https://github.com/QnnOkabayashi/tracing-forest), under its MIT
15//! license. It does not require that crate's procedural macros or an asynchronous runtime.
16//! Enable `forest` for collection and plain formatting, or `forest-ansi` for terminal colors.
17//!
18//! # Recording fields and filtering output
19//!
20//! Span fields can be populated or updated after creation with [`tracing::Span::record`]
21//! or [`crate::Span::record`]. Declare fields whose values are not yet known with
22//! [`tracing::field::Empty`]. A completed tree retains the most recently recorded value
23//! for each field key.
24//!
25//! [`printer::Pretty::with_max_level`] limits the levels displayed by a printer while
26//! retaining the complete collected tree for other uses:
27//!
28//! ```
29//! use gix_trace::forest::{Printer, printer::Pretty};
30//! use tracing_subscriber::filter::LevelFilter;
31//!
32//! let printer = Printer::new().formatter(Pretty.with_max_level(LevelFilter::INFO));
33//! ```
34//!
35//! Filtering happens before rendering. Visible descendants of a hidden span are
36//! promoted to their nearest visible ancestor. Durations and percentages still refer
37//! to the original complete tree and its root, including time in hidden spans.
38//!
39//! # Connecting worker threads to their parent span
40//!
41//! Threads do not inherit the current span or a scoped default subscriber. Wrap the
42//! thread's closure with [`crate::in_thread()`] before spawning to capture both and
43//! restore them in the worker. Spans created in the worker then inherit the parent:
44//!
45//! ```
46//! use gix_error::{message, ErrorExt};
47//! use gix_trace::{ForestLayer, forest::processor};
48//! use std::{sync::mpsc, thread};
49//! use tracing_subscriber::{layer::SubscriberExt, Registry};
50//!
51//! let (sender, finished) = mpsc::channel();
52//! let layer = ForestLayer::from(processor::from_fn(move |tree| {
53//!     sender.send(tree).map_err(|err| {
54//!         processor::error(err.0, message("tree receiver dropped").raise())
55//!     })
56//! }));
57//! let subscriber = Registry::default().with(layer);
58//!
59//! tracing::subscriber::with_default(subscriber, || {
60//!     let root = gix_trace::coarse!("operation");
61//!     let worker = thread::spawn(gix_trace::in_thread(|| {
62//!         let _worker = gix_trace::coarse!("worker");
63//!         gix_trace::info!("work completed");
64//!     }));
65//!     worker.join().expect("worker must finish without panicking");
66//!     drop(root);
67//! });
68//!
69//! let tree = finished.try_recv()?;
70//! let root = tree.span()?;
71//! assert_eq!(root.name(), "operation");
72//! assert_eq!(root.nodes()[0].span()?.name(), "worker");
73//! # Ok::<(), Box<dyn std::error::Error>>(())
74//! ```
75//!
76//! [`crate::Span`] is already an entered guard when tracing is enabled and must stay on
77//! its creating thread. [`crate::in_thread()`] transfers an ordinary [`tracing::Span`]
78//! handle and enters it on the worker. [`tracing::Span::follows_from`] records a causal relation;
79//! it does not establish the parent relationship used to build these trees.
80//!
81//! A span closes only after all its handles and child references are dropped. Leaving
82//! an entered scope alone may therefore leave a tree buffered, and a worker can keep
83//! its parent open after the spawning thread drops its own handle. Drop worker and
84//! parent handles before leaving the installed dispatch (as [`crate::in_thread()`] does), then join workers before
85//! inspecting completed output. Child spans are attached in completion order, which
86//! can differ from their creation order across threads.
87//!
88//! Each span measures time while at least one of its entries is active. Nested or
89//! concurrent entries of the same span count overlapping intervals only once. Separate
90//! child spans' durations are added together, and a parent's total is raised to at least
91//! that sum. Overlapping workers can therefore produce a total larger than elapsed
92//! wall-clock time. These durations describe aggregate tracing activity, not CPU time.
93//! Giving each worker its own child span makes that worker's events and activity visible
94//! separately.
95//!
96//! # CPU time
97//!
98//! Enable `forest-cpu-time` to also collect user and kernel CPU time on Linux, macOS,
99//! FreeBSD, and OpenBSD. Each thread charges CPU time to its most recently entered
100//! distinct forest span. Re-entering an active ancestor keeps its child current.
101//! Concurrent entries contribute independently; suspended futures accumulate no CPU
102//! time between polls. Time blocked on I/O or sleeping is excluded, as is CPU work in
103//! uninstrumented worker threads and child processes.
104//!
105//! A completed `tree::Span` exposes `base_cpu_time()` for its own work,
106//! `inner_cpu_time()` for its children's work, and `total_cpu_time()` for their sum.
107//! The sum includes parallel children and children running while their parent is not
108//! entered. CPU accounting is separate from the existing elapsed-time measurements.
109//! The pretty printer appends inclusive times as `[ user: 12.00ms | sys: 3.00ms ]`.
110//!
111//! Sampling adds a system call on entry and exit, and tracing overhead contributes
112//! to measured CPU time. OS accounting resolution can make short spans measure as
113//! zero. Unsupported platforms and incomplete measurements return `None`, and the
114//! pretty printer omits CPU times. Disabling the feature removes CPU sampling and its state.
115
116#[cfg(feature = "forest-cpu-time")]
117mod cpu;
118mod fail;
119mod layer;
120pub mod printer;
121pub mod processor;
122pub mod tag;
123pub mod tree;
124
125pub use layer::{init, test_init};
126
127/// A node in the log tree, consisting of either a [`Span`](tree::Span) or an [`Event`](tree::Event).
128///
129/// The inner types can be extracted through a `match` statement. Alternatively,
130/// the [`event`] and [`span`] methods provide access to a node of an expected kind.
131///
132/// [`event`]: Tree::event
133/// [`span`]: Tree::span
134#[derive(Clone, Debug)]
135#[allow(clippy::large_enum_variant)] // https://github.com/rust-lang/rust-clippy/issues/9798
136pub enum Tree {
137    /// An [`Event`](tree::Event) leaf node.
138    Event(tree::Event),
139
140    /// A [`Span`](tree::Span) inner node.
141    Span(tree::Span),
142}
143
144/// A trait for processing completed [`Tree`]s.
145///
146/// `Processor`s are responsible for both formatting and writing logs to their
147/// intended destinations. This is typically implemented using
148/// [`Formatter`], [`MakeWriter`], and [`io::Write`].
149///
150/// While this trait may be implemented on downstream types, [`processor::from_fn`]
151/// provides a convenient interface for creating `Processor`s without having to
152/// explicitly define new types.
153///
154/// [trace trees]: crate::forest::Tree
155/// [`Formatter`]: crate::forest::Formatter
156/// [`MakeWriter`]: tracing_subscriber::fmt::MakeWriter
157/// [`io::Write`]: std::io::Write
158pub trait Processor: 'static + Sized {
159    /// Process a [`Tree`]. This can mean many things, such as writing to
160    /// stdout or a file, sending over a network, storing in memory, ignoring,
161    /// or anything else.
162    ///
163    /// # Errors
164    ///
165    /// If the `Tree` cannot be processed, then it is returned along with a
166    /// [`gix_error::Error`]. If the processor is configured with a
167    /// fallback processor from [`Processor::or`], then the `Tree` is deferred
168    /// to that processor.
169    #[allow(clippy::result_large_err)]
170    fn process(&self, tree: Tree) -> processor::Result;
171
172    /// Returns a `Processor` that first attempts processing with `self`, and
173    /// resorts to processing with `fallback` on failure.
174    ///
175    /// Note that [`or_stdout`], [`or_stderr`], and [`or_none`] can be used as
176    /// shortcuts for pretty printing or dropping the `Tree` entirely.
177    ///
178    /// [`or_stdout`]: Processor::or_stdout
179    /// [`or_stderr`]: Processor::or_stderr
180    /// [`or_none`]: Processor::or_none
181    fn or<P: Processor>(self, processor: P) -> processor::WithFallback<Self, P> {
182        processor::WithFallback {
183            primary: self,
184            fallback: processor,
185        }
186    }
187
188    /// Returns a `Processor` that first attempts processing with `self`, and
189    /// resorts to pretty-printing to stdout on failure.
190    fn or_stdout(self) -> processor::WithFallback<Self, Printer<printer::Pretty, printer::MakeStdout>> {
191        self.or(Printer::new().writer(printer::MakeStdout))
192    }
193
194    /// Returns a `Processor` that first attempts processing with `self`, and
195    /// resorts to pretty-printing to stderr on failure.
196    fn or_stderr(self) -> processor::WithFallback<Self, Printer<printer::Pretty, printer::MakeStderr>> {
197        self.or(Printer::new().writer(printer::MakeStderr))
198    }
199
200    /// Returns a `Processor` that first attempts processing with `self`, otherwise
201    /// silently fails.
202    fn or_none(self) -> processor::WithFallback<Self, processor::Sink> {
203        self.or(processor::Sink)
204    }
205}
206
207/// Format a [`Tree`] into a `String`.
208///
209/// This trait is implemented for all `Fn(&Tree) -> Result<String, E>` types, where `E: Error + Send + Sync`.
210pub trait Formatter {
211    /// The error type if the `Tree` cannot be stringified.
212    type Error: std::error::Error + Send + Sync;
213
214    /// Stringifies the `Tree`, or returns an error.
215    ///
216    /// # Errors
217    ///
218    /// If the `Tree` cannot be formatted to a string, an error is returned.
219    fn fmt(&self, tree: &Tree) -> Result<String, Self::Error>;
220}
221
222/// A [`Processor`] that formats and writes logs.
223#[derive(Clone, Debug)]
224pub struct Printer<F, W> {
225    formatter: F,
226    make_writer: W,
227}
228
229/// A [`Processor`] that pretty-prints to stdout.
230pub type PrettyPrinter = Printer<printer::Pretty, printer::MakeStdout>;
231
232/// A [`Processor`] that captures logs during tests and allows them to be presented
233/// when `--nocapture` is used.
234#[derive(Clone, Debug)]
235pub struct TestCapturePrinter<F> {
236    formatter: F,
237}
238
239/// A basic `Copy` type containing information about where an event occurred.
240///
241/// See the [module-level documentation](mod@crate::forest::tag) for more details.
242#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
243pub struct Tag {
244    /// Optional prefix for the tag message
245    prefix: Option<&'static str>,
246
247    /// Level specifying the importance of the log.
248    ///
249    /// This value isn't necessarily "trace", "debug", "info", "warn", or "error",
250    /// and can be customized.
251    suffix: &'static str,
252
253    /// An icon, typically emoji, that represents the tag.
254    icon: char,
255}
256
257/// A type that can parse [`Tag`]s from Tracing events.
258///
259/// This trait is blanket-implemented for all `Fn(&tracing::Event) -> Option<Tag>`,
260/// so top-level `fn`s can be used.
261///
262/// See the [module-level documentation](mod@crate::forest::tag) for more details.
263pub trait TagParser: 'static {
264    /// Parse a tag from a [`tracing::Event`]
265    fn parse(&self, event: &tracing::Event) -> Option<Tag>;
266}
267
268/// A `TagParser` that always returns `None`.
269#[derive(Clone, Debug)]
270pub struct NoTag;
271
272/// Bring forest, tracing, and subscriber extension traits into scope anonymously.
273pub mod traits {
274    pub use super::Processor as _;
275    pub use tracing::Instrument as _;
276    pub use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _};
277}