1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
//! The core tree structure of `tracing-forest`.
//!
//! This module provides methods used for log inspection when using [`capture`].
//! It consists of three types: [`Tree`], [`Span`], and [`Event`].
//!
//! [`capture`]: crate::runtime::capture
use crate::tag::Tag;
#[cfg(feature = "chrono")]
use chrono::{DateTime, Utc};
#[cfg(feature = "serde")]
use serde::Serialize;
use std::time::Duration;
use thiserror::Error;
use tracing::Level;
#[cfg(feature = "uuid")]
use uuid::Uuid;

mod field;
#[cfg(feature = "serde")]
mod ser;

pub use field::Field;
pub(crate) use field::FieldSet;

/// A node in the log tree, consisting of either a [`Span`] or an [`Event`].
///
/// The inner types can be extracted through a `match` statement. Alternatively,
/// the [`event`] and [`span`] methods provide a more ergonomic way to access the
/// inner types in unit tests when combined with the [`capture`] function.
///
/// [`event`]: Tree::event
/// [`span`]: Tree::span
/// [`capture`]: crate::runtime::capture
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[allow(clippy::large_enum_variant)] // https://github.com/rust-lang/rust-clippy/issues/9798
pub enum Tree {
    /// An [`Event`] leaf node.
    Event(Event),

    /// A [`Span`] inner node.
    Span(Span),
}

/// A leaf node in the log tree carrying information about a Tracing event.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Event {
    /// Shared fields between events and spans.
    #[cfg_attr(feature = "serde", serde(flatten))]
    pub(crate) shared: Shared,

    /// The message associated with the event.
    pub(crate) message: Option<String>,

    /// The tag that the event was collected with.
    pub(crate) tag: Option<Tag>,
}

/// An internal node in the log tree carrying information about a Tracing span.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Span {
    /// Shared fields between events and spans.
    #[cfg_attr(feature = "serde", serde(flatten))]
    pub(crate) shared: Shared,

    /// The name of the span.
    pub(crate) name: &'static str,

    /// The total duration the span was open for.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "nanos_total", serialize_with = "ser::nanos")
    )]
    pub(crate) total_duration: Duration,

    /// The total duration inner spans were open for.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "nanos_nested", serialize_with = "ser::nanos")
    )]
    pub(crate) inner_duration: Duration,

    /// Events and spans collected while the span was open.
    pub(crate) nodes: Vec<Tree>,
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub(crate) struct Shared {
    /// The ID of the event or span.
    #[cfg(feature = "uuid")]
    pub(crate) uuid: Uuid,

    /// When the event occurred or when the span opened.
    #[cfg(feature = "chrono")]
    #[cfg_attr(feature = "serde", serde(serialize_with = "ser::timestamp"))]
    pub(crate) timestamp: DateTime<Utc>,

    /// The level the event or span occurred at.
    #[cfg_attr(feature = "serde", serde(serialize_with = "ser::level"))]
    pub(crate) level: Level,

    /// Key-value data.
    #[cfg_attr(feature = "serde", serde(serialize_with = "ser::fields"))]
    pub(crate) fields: FieldSet,
}

/// Error returned by [`Tree::event`][event].
///
/// [event]: crate::tree::Tree::event
#[derive(Error, Debug)]
#[error("Expected an event, found a span")]
pub struct ExpectedEventError(());

/// Error returned by [`Tree::span`][span].
///
/// [span]: crate::tree::Tree::span
#[derive(Error, Debug)]
#[error("Expected a span, found an event")]
pub struct ExpectedSpanError(());

impl Tree {
    /// Returns a reference to the inner [`Event`] if the tree is an event.
    ///
    /// # Errors
    ///
    /// This function returns an error if the `Tree` contains the `Span` variant.
    ///
    /// # Examples
    ///
    /// Inspecting a `Tree` returned from [`capture`]:
    /// ```
    /// use tracing::{info, info_span};
    /// use tracing_forest::tree::{Tree, Event};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let logs: Vec<Tree> = tracing_forest::capture()
    ///         .build()
    ///         .on(async {
    ///             info!("some information");
    ///         })
    ///         .await;
    ///
    ///     assert!(logs.len() == 1);
    ///
    ///     let event: &Event = logs[0].event()?;
    ///     assert!(event.message() == Some("some information"));
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    /// [`capture`]: crate::runtime::capture
    pub fn event(&self) -> Result<&Event, ExpectedEventError> {
        match self {
            Tree::Event(event) => Ok(event),
            Tree::Span(_) => Err(ExpectedEventError(())),
        }
    }

    /// Returns a reference to the inner [`Span`] if the tree is a span.
    ///
    /// # Errors
    ///
    /// This function returns an error if the `Tree` contains the `Event` variant.
    ///
    /// # Examples
    ///
    /// Inspecting a `Tree` returned from [`capture`]:
    /// ```
    /// use tracing::{info, info_span};
    /// use tracing_forest::tree::{Tree, Span};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let logs: Vec<Tree> = tracing_forest::capture()
    ///         .build()
    ///         .on(async {
    ///             info_span!("my_span").in_scope(|| {
    ///                 info!("inside the span");
    ///             });
    ///         })
    ///         .await;
    ///
    ///     assert!(logs.len() == 1);
    ///
    ///     let my_span: &Span = logs[0].span()?;
    ///     assert!(my_span.name() == "my_span");
    ///     Ok(())
    /// }
    /// ```
    ///
    /// [`capture`]: crate::runtime::capture
    pub fn span(&self) -> Result<&Span, ExpectedSpanError> {
        match self {
            Tree::Event(_) => Err(ExpectedSpanError(())),
            Tree::Span(span) => Ok(span),
        }
    }
}

impl Event {
    /// Returns the event's [`Uuid`].
    #[cfg(feature = "uuid")]
    pub fn uuid(&self) -> Uuid {
        self.shared.uuid
    }

    /// Returns the [`DateTime`] that the event occurred at.
    #[cfg(feature = "chrono")]
    pub fn timestamp(&self) -> DateTime<Utc> {
        self.shared.timestamp
    }

    /// Returns the event's [`Level`].
    pub fn level(&self) -> Level {
        self.shared.level
    }

    /// Returns the event's message, if there is one.
    pub fn message(&self) -> Option<&str> {
        self.message.as_deref()
    }

    /// Returns the event's [`Tag`], if there is one.
    pub fn tag(&self) -> Option<Tag> {
        self.tag
    }

    /// Returns the event's fields.
    pub fn fields(&self) -> &[Field] {
        &self.shared.fields
    }
}

impl Span {
    pub(crate) fn new(shared: Shared, name: &'static str) -> Self {
        Span {
            shared,
            name,
            total_duration: Duration::ZERO,
            inner_duration: Duration::ZERO,
            nodes: Vec::new(),
        }
    }

    /// Returns the span's [`Uuid`].
    #[cfg(feature = "uuid")]
    pub fn uuid(&self) -> Uuid {
        self.shared.uuid
    }

    /// Returns the [`DateTime`] that the span occurred at.
    #[cfg(feature = "chrono")]
    pub fn timestamp(&self) -> DateTime<Utc> {
        self.shared.timestamp
    }

    /// Returns the span's [`Level`].
    pub fn level(&self) -> Level {
        self.shared.level
    }

    /// Returns the span's name.
    pub fn name(&self) -> &str {
        self.name
    }

    /// Returns the span's child trees.
    pub fn nodes(&self) -> &[Tree] {
        &self.nodes
    }

    /// Returns the total duration the span was entered for.
    ///
    /// If the span was used to instrument a `Future`, this only accounts for the
    /// time spent polling the `Future`. For example, time spent sleeping will
    /// not be accounted for.
    pub fn total_duration(&self) -> Duration {
        self.total_duration
    }

    /// Returns the duration that inner spans were opened for.
    pub fn inner_duration(&self) -> Duration {
        self.inner_duration
    }

    /// Returns the duration this span was entered, but not in any child spans.
    pub fn base_duration(&self) -> Duration {
        self.total_duration - self.inner_duration
    }
}