Skip to main content

gix_trace/forest/printer/
pretty.rs

1use crate::forest::{
2    Formatter, Tag, Tree,
3    tree::{Event, Shared, Span},
4};
5use std::fmt::{self, Write};
6use tracing::metadata::LevelFilter;
7
8type IndentVec = smallvec::SmallVec<[Indent; 32]>;
9
10#[cfg(feature = "forest-ansi")]
11use nu_ansi_term::Color;
12#[cfg(feature = "forest-ansi")]
13use tracing::Level;
14
15/// Format logs for pretty printing.
16///
17/// # Interpreting span times
18///
19/// Spans have the following format:
20/// ```txt
21/// <NAME> [ <DURATION> | <BODY> / <ROOT> ]
22/// ```
23/// * DURATION represents elapsed time while the span has at least one active entry.
24///   Overlapping entries into the same span count once. If the span instruments a
25///   `Future`, time between polls does not count because the span is not entered then.
26/// * BODY represents the percent time the span is entered relative to the root
27///   span, *excluding* time that any child spans are entered.
28/// * ROOT represents the percent time the span is entered relative to the root
29///   span, *including* time that any child spans are entered.
30///
31/// As a mental model, look at `ROOT` to quickly narrow down which branches are
32/// costly, and look at `BODY` to pinpoint exactly which spans are expensive.
33///
34/// Spans without any child spans would have the same `BODY` and `ROOT`, so the
35/// redundancy is omitted.
36/// Durations accumulate child work: overlapping children contribute separately,
37/// and a parent's total is raised to at least their sum. Totals can therefore
38/// exceed wall-clock time; see [`Span::total_duration`].
39/// A root with zero duration displays `0.00%` for all percentages.
40///
41/// With `forest-cpu-time`, an additional `[ user: <TIME> | sys: <TIME> ]` shows
42/// inclusive user and kernel CPU time. This is omitted on unsupported platforms
43/// or when measurements are incomplete. CPU times exclude blocked time and
44/// include parallel children; elapsed-time percentages are unchanged.
45///
46/// Use [`Pretty::with_max_level`] to omit less important nodes from the output
47/// while retaining their more important descendants and the original durations.
48///
49/// # Examples
50///
51/// An arbitrarily complex example:
52/// ```log
53/// INFO     try_from_entry_ro [ 324µs | 8.47% / 100.00% ]
54/// INFO     ┝━ server::internal_search [ 296µs | 19.02% / 91.53% ]
55/// INFO     │  ┝━ i [filter.info]: Some filter info...
56/// INFO     │  ┝━ server::search [ 226µs | 10.11% / 70.01% ]
57/// INFO     │  │  ┝━ be::search [ 181µs | 6.94% / 55.85% ]
58/// INFO     │  │  │  ┕━ be::search -> filter2idl [ 158µs | 19.65% / 48.91% ]
59/// INFO     │  │  │     ┝━ be::idl_arc_sqlite::get_idl [ 20.4µs | 6.30% ]
60/// INFO     │  │  │     │  ┕━ i [filter.info]: Some filter info...
61/// INFO     │  │  │     ┕━ be::idl_arc_sqlite::get_idl [ 74.3µs | 22.96% ]
62/// ERROR    │  │  │        ┝━ 🚨 [admin.error]: On no, an admin error occurred :(
63/// DEBUG    │  │  │        ┝━ 🐛 [debug]: An untagged debug log
64/// INFO     │  │  │        ┕━ i [admin.info]: there's been a big mistake | alive: false | status: "very sad"
65/// INFO     │  │  ┕━ be::idl_arc_sqlite::get_identry [ 13.1µs | 4.04% ]
66/// ERROR    │  │     ┝━ 🔐 [security.critical]: A security critical log
67/// INFO     │  │     ┕━ 🔓 [security.access]: A security access log
68/// INFO     │  ┕━ server::search<filter_resolve> [ 8.08µs | 2.50% ]
69/// WARN     │     ┕━ 🚧 [filter.warn]: Some filter warning
70/// TRACE    ┕━ 📍 [trace]: Finished!
71/// ```
72#[derive(Debug)]
73pub struct Pretty;
74
75impl Formatter for Pretty {
76    type Error = fmt::Error;
77
78    fn fmt(&self, tree: &Tree) -> Result<String, fmt::Error> {
79        Pretty.with_max_level(LevelFilter::TRACE).fmt(tree)
80    }
81}
82
83/// Pretty-print only nodes at or above a selected importance level.
84///
85/// Construct this formatter with [`Pretty::with_max_level`]. Hidden spans' visible
86/// descendants are promoted to their nearest visible ancestor, or to the top level
87/// if there is none. Percentages retain the full, unfiltered root's duration.
88#[derive(Debug)]
89pub struct FilteredPretty {
90    max_level: LevelFilter,
91}
92
93impl Formatter for FilteredPretty {
94    type Error = fmt::Error;
95
96    fn fmt(&self, tree: &Tree) -> Result<String, fmt::Error> {
97        if self.max_level == LevelFilter::OFF {
98            return Ok(String::new());
99        }
100        let mut writer = String::with_capacity(256);
101        let root_duration = match tree {
102            Tree::Span(span) => span.total_duration().as_nanos() as f64,
103            Tree::Event(_) => 0.0,
104        };
105        let mut indent = IndentVec::new();
106        for node in visible_nodes(std::slice::from_ref(tree), self.max_level) {
107            Pretty::format_tree(node, root_duration, self.max_level, &mut indent, &mut writer)?;
108        }
109        Ok(writer)
110    }
111}
112
113impl Pretty {
114    /// Select the most verbose level to include in formatted output.
115    ///
116    /// For example, [`LevelFilter::WARN`] retains warnings and errors. Visible
117    /// descendants of omitted spans are promoted without changing their order or
118    /// the durations used for percentages. [`LevelFilter::OFF`] produces an empty
119    /// string, and [`LevelFilter::TRACE`] produces the same output as `Pretty`.
120    /// This filters formatting only; the collected tree is unchanged.
121    ///
122    /// ```
123    /// use gix_trace::forest::{Printer, printer::Pretty};
124    /// use tracing::metadata::LevelFilter;
125    ///
126    /// let printer = Printer::new().formatter(Pretty.with_max_level(LevelFilter::WARN));
127    /// ```
128    pub const fn with_max_level(self, max_level: LevelFilter) -> FilteredPretty {
129        FilteredPretty { max_level }
130    }
131
132    fn format_tree(
133        tree: &Tree,
134        root_duration: f64,
135        max_level: LevelFilter,
136        indent: &mut IndentVec,
137        writer: &mut String,
138    ) -> fmt::Result {
139        match tree {
140            Tree::Event(event) => {
141                Pretty::format_shared(&event.shared, writer)?;
142                Pretty::format_indent(indent, writer)?;
143                Pretty::format_event(event, writer)
144            }
145            Tree::Span(span) => {
146                Pretty::format_shared(&span.shared, writer)?;
147                Pretty::format_indent(indent, writer)?;
148                Pretty::format_span(span, root_duration, max_level, indent, writer)
149            }
150        }
151    }
152
153    fn format_shared(shared: &Shared, writer: &mut String) -> fmt::Result {
154        #[cfg(feature = "forest-ansi")]
155        let level = ColorLevel(shared.level);
156        #[cfg(not(feature = "forest-ansi"))]
157        let level = shared.level;
158        write!(writer, "{level:<8} ")
159    }
160
161    fn format_indent(indent: &[Indent], writer: &mut String) -> fmt::Result {
162        for indent in indent {
163            writer.write_str(indent.repr())?;
164        }
165        Ok(())
166    }
167
168    fn format_event(event: &Event, writer: &mut String) -> fmt::Result {
169        let tag = event.tag().unwrap_or_else(|| Tag::from(event.level()));
170
171        write!(writer, "{} [{tag}]: ", tag.icon())?;
172
173        if let Some(message) = event.message() {
174            writer.write_str(message)?;
175        }
176
177        for field in event.fields() {
178            write!(writer, " | {}: {}", FieldKey(field.key()), field.value())?;
179        }
180
181        writeln!(writer)
182    }
183
184    fn format_span(
185        span: &Span,
186        root_duration: f64,
187        max_level: LevelFilter,
188        indent: &mut IndentVec,
189        writer: &mut String,
190    ) -> fmt::Result {
191        let total_duration = span.total_duration().as_nanos() as f64;
192        let inner_duration = span.inner_duration().as_nanos() as f64;
193        let percentage = |duration| {
194            if root_duration == 0.0 {
195                0.0
196            } else {
197                100.0 * duration / root_duration
198            }
199        };
200        let percent_total_of_root_duration = percentage(total_duration);
201
202        write!(writer, "{} [ {} | ", span.name(), DurationDisplay(total_duration))?;
203
204        if inner_duration > 0.0 {
205            let base_duration = span.base_duration().as_nanos() as f64;
206            let percent_base_of_root_duration = percentage(base_duration);
207            write!(writer, "{percent_base_of_root_duration:.2}% / ")?;
208        }
209
210        write!(writer, "{percent_total_of_root_duration:.2}% ]")?;
211
212        #[cfg(feature = "forest-cpu-time")]
213        if let Some(cpu) = span.total_cpu_time() {
214            write!(
215                writer,
216                " [ user: {} | sys: {} ]",
217                DurationDisplay(cpu.user.as_nanos() as f64),
218                DurationDisplay(cpu.system.as_nanos() as f64),
219            )?;
220        }
221
222        for (n, field) in span.shared.fields.iter().enumerate() {
223            write!(
224                writer,
225                "{} {}: {}",
226                if n == 0 { "" } else { " |" },
227                FieldKey(field.key()),
228                field.value()
229            )?;
230        }
231        writeln!(writer)?;
232
233        let mut children = visible_nodes(span.nodes(), max_level).peekable();
234        if children.peek().is_some() {
235            match indent.last_mut() {
236                Some(edge @ Indent::Turn) => *edge = Indent::Null,
237                Some(edge @ Indent::Fork) => *edge = Indent::Line,
238                _ => {}
239            }
240
241            indent.push(Indent::Fork);
242
243            while let Some(tree) = children.next() {
244                if let Some(edge) = indent.last_mut() {
245                    *edge = if children.peek().is_some() {
246                        Indent::Fork
247                    } else {
248                        Indent::Turn
249                    };
250                }
251                Pretty::format_tree(tree, root_duration, max_level, indent, writer)?;
252            }
253
254            indent.pop();
255        }
256
257        Ok(())
258    }
259}
260
261fn visible_nodes(nodes: &[Tree], max_level: LevelFilter) -> impl Iterator<Item = &Tree> {
262    let mut stack = smallvec::SmallVec::<[std::slice::Iter<'_, Tree>; 8]>::new();
263    stack.push(nodes.iter());
264    std::iter::from_fn(move || {
265        loop {
266            let nodes = stack.last_mut()?;
267            let Some(tree) = nodes.next() else {
268                stack.pop();
269                continue;
270            };
271            match tree {
272                Tree::Event(event) if event.level() <= max_level => return Some(tree),
273                Tree::Span(span) if span.level() <= max_level => return Some(tree),
274                Tree::Span(span) => stack.push(span.nodes().iter()),
275                Tree::Event(_) => {}
276            }
277        }
278    })
279}
280
281enum Indent {
282    Null,
283    Line,
284    Fork,
285    Turn,
286}
287
288impl Indent {
289    fn repr(&self) -> &'static str {
290        match self {
291            Self::Null => "   ",
292            Self::Line => "│  ",
293            Self::Fork => "┝━ ",
294            Self::Turn => "┕━ ",
295        }
296    }
297}
298
299struct DurationDisplay(f64);
300
301// Taken from chrono
302impl fmt::Display for DurationDisplay {
303    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
304        let mut t = self.0;
305        for unit in ["ns", "µs", "ms", "s"] {
306            if t < 10.0 {
307                return write!(f, "{t:.2}{unit}");
308            } else if t < 100.0 {
309                return write!(f, "{t:.1}{unit}");
310            } else if t < 1000.0 {
311                return write!(f, "{t:.0}{unit}");
312            }
313            t /= 1000.0;
314        }
315        write!(f, "{:.0}s", t * 1000.0)
316    }
317}
318
319/// Implements colored formatting for a field if enabled
320struct FieldKey<'a>(&'a str);
321
322impl fmt::Display for FieldKey<'_> {
323    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324        #[cfg(feature = "forest-ansi")]
325        {
326            let color = Color::White.dimmed();
327
328            write!(f, "{}{}{}", color.prefix(), self.0, color.suffix())
329        }
330        #[cfg(not(feature = "forest-ansi"))]
331        {
332            f.write_str(self.0)
333        }
334    }
335}
336
337// From tracing-tree
338#[cfg(feature = "forest-ansi")]
339struct ColorLevel(Level);
340
341#[cfg(feature = "forest-ansi")]
342impl fmt::Display for ColorLevel {
343    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344        let color = match self.0 {
345            Level::TRACE => Color::Purple,
346            Level::DEBUG => Color::Blue,
347            Level::INFO => Color::Green,
348            Level::WARN => Color::Rgb(252, 234, 160), // orange
349            Level::ERROR => Color::Red,
350        };
351        let style = color.bold();
352        write!(f, "{}", style.prefix())?;
353        f.pad(self.0.as_str())?;
354        write!(f, "{}", style.suffix())
355    }
356}
357
358#[cfg(all(test, feature = "forest-cpu-time"))]
359mod tests {
360    use super::*;
361
362    #[test]
363    fn unavailable_cpu_time_is_omitted() -> gix_error::TestResult {
364        let zero = Some(crate::forest::tree::CpuTime::default());
365        for (base, inner) in [(None, None), (None, zero), (zero, None)] {
366            let mut span = Span::new(
367                Shared {
368                    level: tracing::Level::INFO,
369                    fields: Default::default(),
370                },
371                "operation",
372            );
373            span.base_cpu_time = base;
374            span.inner_cpu_time = inner;
375            let rendered = Pretty.fmt(&Tree::Span(span))?;
376            assert!(
377                rendered.ends_with("operation [ 0.00ns | 0.00% ]\n"),
378                "missing own or child CPU measurements leave only elapsed timing: {rendered:?}"
379            );
380        }
381        Ok(())
382    }
383}