Skip to main content

gix_trace/forest/
layer.rs

1use crate::ForestLayer;
2use crate::forest::processor::Sink;
3use crate::forest::tree::{self, FieldSet};
4use crate::forest::{NoTag, PrettyPrinter, Processor, Tag, TagParser, TestCapturePrinter, Tree, fail};
5use std::fmt;
6use std::io::{self, Write};
7use std::time::Instant;
8use tracing::field::{Field, Visit};
9use tracing::span::{Attributes, Id, Record};
10use tracing::{Event, Subscriber};
11use tracing_subscriber::layer::{Context, Layer, SubscriberExt};
12use tracing_subscriber::registry::{LookupSpan, Registry, SpanRef};
13use tracing_subscriber::util::SubscriberInitExt;
14use tracing_subscriber::util::TryInitError;
15
16pub(crate) struct OpenedSpan {
17    span: tree::Span,
18    start: Instant,
19    active_entries: usize,
20    #[cfg(feature = "forest-cpu-time")]
21    cpu: super::cpu::Span,
22}
23
24impl OpenedSpan {
25    fn new(attrs: &Attributes<'_>) -> Self {
26        let mut fields = FieldSet::default();
27        attrs.record(&mut |field: &Field, value: &dyn fmt::Debug| {
28            fields.push(tree::Field::new(field.name(), format!("{value:?}")));
29        });
30        OpenedSpan {
31            span: tree::Span::new(
32                tree::Shared {
33                    level: *attrs.metadata().level(),
34                    fields,
35                },
36                attrs.metadata().name(),
37            ),
38            start: Instant::now(),
39            active_entries: 0,
40            #[cfg(feature = "forest-cpu-time")]
41            cpu: super::cpu::Span::default(),
42        }
43    }
44
45    fn enter(&mut self, now: Instant) {
46        self.active_entries = self
47            .active_entries
48            .checked_add(1)
49            .expect("each active span entry requires a live guard, so the count fits in usize");
50        if self.active_entries == 1 {
51            self.start = now;
52        }
53        #[cfg(feature = "forest-cpu-time")]
54        self.cpu.enter();
55    }
56
57    fn exit(&mut self, now: Instant) {
58        #[cfg(feature = "forest-cpu-time")]
59        self.cpu.exit();
60        self.active_entries = self
61            .active_entries
62            .checked_sub(1)
63            .expect("tracing exits a span only after entering it");
64        if self.active_entries == 0 {
65            self.span.total_duration += now.duration_since(self.start);
66        }
67    }
68
69    fn close(self) -> tree::Span {
70        #[cfg(feature = "forest-cpu-time")]
71        {
72            let mut span = self.span;
73            span.base_cpu_time = self.cpu.time();
74            span
75        }
76        #[cfg(not(feature = "forest-cpu-time"))]
77        self.span
78    }
79
80    fn record_event(&mut self, event: tree::Event) {
81        self.span.nodes.push(Tree::Event(event));
82    }
83
84    fn record_span(&mut self, span: tree::Span) {
85        self.span.inner_duration += span.total_duration();
86        #[cfg(feature = "forest-cpu-time")]
87        {
88            self.span.inner_cpu_time = self
89                .span
90                .inner_cpu_time
91                .zip(span.total_cpu_time())
92                .and_then(|(total, child)| total.checked_add(child));
93        }
94        self.span.nodes.push(Tree::Span(span));
95    }
96}
97
98impl<P: Processor, T: TagParser> ForestLayer<P, T> {
99    /// Create a new `ForestLayer` from a [`Processor`] and a [`TagParser`].
100    pub fn new(processor: P, tag: T) -> Self {
101        ForestLayer { processor, tag }
102    }
103}
104
105impl<P: Processor> From<P> for ForestLayer<P, NoTag> {
106    fn from(processor: P) -> Self {
107        ForestLayer::new(processor, NoTag)
108    }
109}
110
111impl ForestLayer<Sink, NoTag> {
112    /// Create a new `ForestLayer` that does nothing with collected trace data.
113    pub fn sink() -> Self {
114        ForestLayer::from(Sink)
115    }
116}
117
118impl Default for ForestLayer<PrettyPrinter, NoTag> {
119    fn default() -> Self {
120        ForestLayer {
121            processor: PrettyPrinter::new(),
122            tag: NoTag,
123        }
124    }
125}
126
127impl<P, T, S> Layer<S> for ForestLayer<P, T>
128where
129    P: Processor,
130    T: TagParser,
131    S: Subscriber + for<'a> LookupSpan<'a>,
132{
133    fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
134        let span = ctx.span(id).expect(fail::SPAN_NOT_IN_CONTEXT);
135        let opened = OpenedSpan::new(attrs);
136
137        let mut extensions = span.extensions_mut();
138        extensions.insert(opened);
139    }
140
141    fn on_record(&self, id: &Id, values: &Record<'_>, ctx: Context<'_, S>) {
142        let mut recorded = FieldSet::default();
143        // User-provided Debug implementations can trace into this span again.
144        values.record(&mut |field: &Field, value: &dyn fmt::Debug| {
145            recorded.push(tree::Field::new(field.name(), format!("{value:?}")));
146        });
147        let span = ctx.span(id).expect(fail::SPAN_NOT_IN_CONTEXT);
148        let mut extensions = span.extensions_mut();
149        let fields = &mut extensions
150            .get_mut::<OpenedSpan>()
151            .expect(fail::OPENED_SPAN_NOT_IN_EXTENSIONS)
152            .span
153            .shared
154            .fields;
155        for field in recorded {
156            if let Some(existing) = fields.iter_mut().find(|existing| existing.key() == field.key()) {
157                *existing = field;
158            } else {
159                fields.push(field);
160            }
161        }
162    }
163
164    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
165        struct Visitor {
166            message: Option<String>,
167            fields: FieldSet,
168            immediate: bool,
169        }
170
171        impl Visit for Visitor {
172            fn record_bool(&mut self, field: &Field, value: bool) {
173                match field.name() {
174                    "immediate" => self.immediate |= value,
175                    _ => self.record_debug(field, &value),
176                }
177            }
178
179            fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
180                let value = format!("{value:?}");
181                match field.name() {
182                    "message" if self.message.is_none() => self.message = Some(value),
183                    key => self.fields.push(tree::Field::new(key, value)),
184                }
185            }
186        }
187
188        let mut visitor = Visitor {
189            message: None,
190            fields: FieldSet::default(),
191            immediate: false,
192        };
193
194        event.record(&mut visitor);
195
196        let shared = tree::Shared {
197            level: *event.metadata().level(),
198            fields: visitor.fields,
199        };
200
201        let tree_event = tree::Event {
202            shared,
203            message: visitor.message,
204            tag: self.tag.parse(event),
205        };
206
207        let current_span = ctx.event_span(event);
208
209        if visitor.immediate {
210            write_immediate(&tree_event, current_span.as_ref())
211                .expect("writing an immediate trace event to stderr failed");
212        }
213
214        match current_span.as_ref() {
215            Some(parent) => parent
216                .extensions_mut()
217                .get_mut::<OpenedSpan>()
218                .expect(fail::OPENED_SPAN_NOT_IN_EXTENSIONS)
219                .record_event(tree_event),
220            None => self
221                .processor
222                .process(Tree::Event(tree_event))
223                .expect(fail::PROCESSING_ERROR),
224        }
225    }
226
227    fn on_enter(&self, id: &Id, ctx: Context<'_, S>) {
228        ctx.span(id)
229            .expect(fail::SPAN_NOT_IN_CONTEXT)
230            .extensions_mut()
231            .get_mut::<OpenedSpan>()
232            .expect(fail::OPENED_SPAN_NOT_IN_EXTENSIONS)
233            .enter(Instant::now());
234    }
235
236    fn on_exit(&self, id: &Id, ctx: Context<'_, S>) {
237        ctx.span(id)
238            .expect(fail::SPAN_NOT_IN_CONTEXT)
239            .extensions_mut()
240            .get_mut::<OpenedSpan>()
241            .expect(fail::OPENED_SPAN_NOT_IN_EXTENSIONS)
242            .exit(Instant::now());
243    }
244
245    fn on_close(&self, id: Id, ctx: Context<'_, S>) {
246        let span_ref = ctx.span(&id).expect(fail::SPAN_NOT_IN_CONTEXT);
247
248        let mut span = span_ref
249            .extensions_mut()
250            .remove::<OpenedSpan>()
251            .expect(fail::OPENED_SPAN_NOT_IN_EXTENSIONS)
252            .close();
253
254        // Ensure that the total duration is at least as much as the inner
255        // duration. This is caused by when a child span is manually passed
256        // a parent span and then enters without entering the parent span. Also
257        // when a child span is created within a parent, and then stored and
258        // entered again when the parent isn't opened.
259        //
260        // Issue: https://github.com/QnnOkabayashi/tracing-forest/issues/11
261        if span.total_duration < span.inner_duration {
262            span.total_duration = span.inner_duration;
263        }
264
265        match span_ref.parent() {
266            Some(parent) => parent
267                .extensions_mut()
268                .get_mut::<OpenedSpan>()
269                .expect(fail::OPENED_SPAN_NOT_IN_EXTENSIONS)
270                .record_span(span),
271            None => self.processor.process(Tree::Span(span)).expect(fail::PROCESSING_ERROR),
272        }
273    }
274}
275
276fn write_immediate<S>(event: &tree::Event, current: Option<&SpanRef<'_, S>>) -> io::Result<()>
277where
278    S: for<'a> LookupSpan<'a>,
279{
280    // LEVEL root > inner > leaf > my message here | key: val
281    let mut writer = smallvec::SmallVec::<[u8; 256]>::new();
282
283    write!(writer, "{:<8} ", event.level())?;
284
285    let tag = event.tag().unwrap_or_else(|| Tag::from(event.level()));
286
287    write!(writer, "{icon} IMMEDIATE {icon} ", icon = tag.icon())?;
288
289    if let Some(span) = current {
290        for ancestor in span.scope().from_root() {
291            write!(writer, "{} > ", ancestor.name())?;
292        }
293    }
294
295    if let Some(message) = event.message() {
296        write!(writer, "{message}")?;
297    }
298
299    for field in event.fields() {
300        write!(writer, " | {}: {}", field.key(), field.value())?;
301    }
302
303    writeln!(writer)?;
304
305    io::stderr().write_all(&writer)
306}
307
308/// Initializes a global subscriber with a [`ForestLayer`] using the default configuration.
309///
310/// Completed trees are formatted and written synchronously on the thread that closes
311/// the root span or emits an event outside any span. Configure a [`ForestLayer`]
312/// manually to customize processing and output.
313///
314/// Returns an error if a global subscriber or logger was already installed.
315///
316/// # Examples
317/// ```
318/// use tracing::{info, info_span};
319///
320/// gix_trace::forest::init()?;
321///
322/// info!("Hello, world!");
323/// info_span!("my_span").in_scope(|| {
324///     info!("Relevant information");
325/// });
326/// # Ok::<(), Box<dyn std::error::Error>>(())
327/// ```
328/// Produces output like:
329/// ```log
330/// INFO     i [info]: Hello, world!
331/// INFO     my_span [ 26.0µs | 100.000% ]
332/// INFO     ┕━ i [info]: Relevant information
333/// ```
334pub fn init() -> Result<(), TryInitError> {
335    Registry::default().with(ForestLayer::default()).try_init()
336}
337
338/// Initializes a global subscriber for cargo tests with a [`ForestLayer`] using the default
339/// configuration.
340///
341/// Completed trees are formatted synchronously and printed through the standard
342/// test output capture. Calling this repeatedly is safe; initialization errors are
343/// returned if a global subscriber was already installed.
344///
345/// # Examples
346/// ```
347/// use tracing::{info, info_span};
348///
349/// let _ = gix_trace::forest::test_init();
350///
351/// info!("Hello, world!");
352/// info_span!("my_span").in_scope(|| {
353///     info!("Relevant information");
354/// });
355/// ```
356pub fn test_init() -> Result<(), TryInitError> {
357    Registry::default()
358        .with(ForestLayer::new(TestCapturePrinter::new(), NoTag))
359        .try_init()
360}
361
362#[cfg(test)]
363mod tests {
364    use std::time::{Duration, Instant};
365
366    use super::{OpenedSpan, tree};
367
368    fn span() -> OpenedSpan {
369        OpenedSpan {
370            span: tree::Span::new(
371                tree::Shared {
372                    level: tracing::Level::INFO,
373                    fields: Default::default(),
374                },
375                "operation",
376            ),
377            start: Instant::now(),
378            active_entries: 0,
379            #[cfg(feature = "forest-cpu-time")]
380            cpu: super::super::cpu::Span::default(),
381        }
382    }
383
384    #[test]
385    fn overlapping_and_reentrant_entries_count_elapsed_time_once() {
386        let mut span = span();
387        let start = Instant::now();
388        span.enter(start);
389        span.enter(start + Duration::from_nanos(5));
390        span.enter(start + Duration::from_nanos(9));
391        span.exit(start + Duration::from_nanos(13));
392        span.exit(start + Duration::from_nanos(17));
393        span.exit(start + Duration::from_nanos(23));
394        assert_eq!(
395            span.close().total_duration(),
396            Duration::from_nanos(23),
397            "overlapping entries keep the first start and count until the last exit"
398        );
399    }
400
401    #[test]
402    fn disjoint_entries_exclude_idle_time() {
403        let mut span = span();
404        let start = Instant::now();
405        span.enter(start);
406        span.exit(start + Duration::from_nanos(5));
407        span.enter(start + Duration::from_nanos(20));
408        span.exit(start + Duration::from_nanos(29));
409        assert_eq!(
410            span.close().total_duration(),
411            Duration::from_nanos(14),
412            "separate entry intervals accumulate without the idle gap between them"
413        );
414    }
415}