Skip to main content

gix_trace/forest/
tag.rs

1//! Supplement events with categorical information.
2//!
3//! # Use cases for tags
4//!
5//! Using tags in trace data can improve readability by distinguishing
6//! between different kinds of trace data such as requests, internal state,
7//! or special operations. An error during a network request could mean a
8//! timeout occurred, while an error in the internal state could mean
9//! corruption. Both are errors, but one should be treated more seriously than
10//! the other, and therefore the two should be easily distinguishable.
11//!
12//! # How to use tags
13//!
14//! Every application has its own preferences for how events should be tagged,
15//! and this can be set via a custom [`TagParser`] in the [`ForestLayer`]. This
16//! works by passing a reference to each incoming [`Event`] to the `TagParser`,
17//! which can then be parsed into an `Option<Tag>` for the `ForestLayer` to use
18//! later.
19//!
20//! Since [`TagParser`] is blanket implemented for all `Fn(&Event) -> Option<Tag>`
21//! the easiest way to create one is to define a top-level function with this type
22//! signature.
23//!
24//! Once the function is defined, pass it to [`ForestLayer::new`].
25//!
26//! [`ForestLayer`]: crate::ForestLayer
27//! [`ForestLayer::new`]: crate::ForestLayer::new
28//!
29//! ## Examples
30//!
31//! Declaring and using a custom `TagParser`.
32//! ```
33//! use gix_trace::{ForestLayer, forest::{Printer, Tag}};
34//! use tracing::{error, info, Event, Level};
35//! use tracing_subscriber::layer::SubscriberExt;
36//!
37//! fn simple_tag(event: &Event) -> Option<Tag> {
38//!     let target = event.metadata().target();
39//!     let level = *event.metadata().level();
40//!
41//!     Some(match target {
42//!         "security" if level == Level::ERROR => Tag::builder()
43//!             .prefix(target)
44//!             .suffix("critical")
45//!             .icon('🔐')
46//!             .build(),
47//!         "admin" | "request" => Tag::builder().prefix(target).level(level).build(),
48//!         _ => return None,
49//!     })
50//! }
51//!
52//! let subscriber = tracing_subscriber::registry()
53//!     .with(ForestLayer::new(Printer::new(), simple_tag));
54//! tracing::subscriber::with_default(subscriber, || {
55//!     // The parser uses the target to distinguish event categories.
56//!     info!(target: "admin", "some info for the admin");
57//!     error!(target: "request", "the request timed out");
58//!     error!(target: "security", "the db has been breached");
59//!     info!("no tags here");
60//! });
61//! ```
62//! ```log
63//! INFO     i [admin.info]: some info for the admin
64//! ERROR    🚨 [request.error]: the request timed out
65//! ERROR    🔐 [security.critical]: the db has been breached
66//! INFO     i [info]: no tags here
67//! ```
68use crate::forest::{NoTag, Tag, TagParser};
69use std::fmt;
70use tracing::{Event, Level};
71
72impl Tag {
73    /// Build a new [`Tag`].
74    ///
75    /// # Examples
76    ///
77    /// ```
78    /// use gix_trace::forest::Tag;
79    ///
80    /// let tag = Tag::builder()
81    ///     .prefix("security")
82    ///     .suffix("critical")
83    ///     .icon('🔐')
84    ///     .build();
85    /// ```
86    pub fn builder() -> Builder<(), ()> {
87        Builder {
88            prefix: None,
89            suffix: (),
90            icon: (),
91        }
92    }
93
94    /// Returns the prefix, if there is one.
95    pub const fn prefix(&self) -> Option<&'static str> {
96        self.prefix
97    }
98
99    /// Returns the suffix.
100    pub const fn suffix(&self) -> &'static str {
101        self.suffix
102    }
103
104    /// Returns the icon.
105    pub const fn icon(&self) -> char {
106        self.icon
107    }
108}
109
110/// Incrementally construct [`Tag`]s.
111///
112/// See [`Tag::builder`] for more details.
113#[derive(Copy, Clone, PartialEq, Eq)]
114pub struct Builder<S, I> {
115    prefix: Option<&'static str>,
116    suffix: S,
117    icon: I,
118}
119
120/// A type used by [`Builder`] to indicate that the suffix has been set.
121#[derive(Copy, Clone, PartialEq, Eq)]
122pub struct Suffix(&'static str);
123
124/// A type used by [`Builder`] to indicate that the icon has been set.
125#[derive(Copy, Clone, PartialEq, Eq)]
126pub struct Icon(char);
127
128impl<S, I> Builder<S, I> {
129    /// Set the prefix.
130    pub fn prefix(self, prefix: &'static str) -> Builder<S, I> {
131        Builder {
132            prefix: Some(prefix),
133            ..self
134        }
135    }
136
137    /// Set the suffix.
138    pub fn suffix(self, suffix: &'static str) -> Builder<Suffix, I> {
139        Builder {
140            prefix: self.prefix,
141            suffix: Suffix(suffix),
142            icon: self.icon,
143        }
144    }
145
146    /// Set the icon.
147    pub fn icon(self, icon: char) -> Builder<S, Icon> {
148        Builder {
149            prefix: self.prefix,
150            suffix: self.suffix,
151            icon: Icon(icon),
152        }
153    }
154
155    /// Set the suffix and icon using defaults for each [`Level`].
156    ///
157    /// If the `Tag` won't have a prefix, then `Tag::from(level)` can be used as
158    /// a shorter alternative.
159    pub fn level(self, level: Level) -> Builder<Suffix, Icon> {
160        let (suffix, icon) = match level {
161            Level::TRACE => ("trace", '📍'),
162            Level::DEBUG => ("debug", '🐛'),
163            Level::INFO => ("info", 'i'),
164            Level::WARN => ("warn", '🚧'),
165            Level::ERROR => ("error", '🚨'),
166        };
167
168        Builder {
169            prefix: self.prefix,
170            suffix: Suffix(suffix),
171            icon: Icon(icon),
172        }
173    }
174}
175
176impl Builder<Suffix, Icon> {
177    /// Complete the [`Tag`].
178    ///
179    /// This can only be called once a suffix and an icon have been provided via
180    /// [`.suffix(...)`](Builder::suffix) and [`.icon(...)`](Builder::icon), or
181    /// alternatively just [`.level(...)`](Builder::level).
182    pub fn build(self) -> Tag {
183        Tag {
184            prefix: self.prefix,
185            suffix: self.suffix.0,
186            icon: self.icon.0,
187        }
188    }
189}
190
191impl fmt::Display for Tag {
192    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193        if let Some(prefix) = self.prefix {
194            write!(f, "{prefix}.{}", self.suffix)
195        } else {
196            self.suffix.fmt(f)
197        }
198    }
199}
200
201impl From<Level> for Tag {
202    fn from(level: Level) -> Self {
203        Tag::builder().level(level).build()
204    }
205}
206
207impl TagParser for NoTag {
208    fn parse(&self, _event: &Event) -> Option<Tag> {
209        None
210    }
211}
212
213impl<F> TagParser for F
214where
215    F: 'static + Fn(&Event) -> Option<Tag>,
216{
217    fn parse(&self, event: &Event) -> Option<Tag> {
218        self(event)
219    }
220}