🛈 Note: This is pre-release documentation for the upcoming tracing 0.2.0 ecosystem.

For the release documentation, please see docs.rs, instead.

tracing_subscriber/fmt/format/
mod.rs

1//! Formatters for logging `tracing` events.
2//!
3//! This module provides several formatter implementations, as well as utilities
4//! for implementing custom formatters.
5//!
6//! # Formatters
7//! This module provides a number of formatter implementations:
8//!
9//! * [`Full`]: The default formatter. This emits human-readable,
10//!   single-line logs for each event that occurs, with the current span context
11//!   displayed before the formatted representation of the event. See
12//!   [here](Full#example-output) for sample output.
13//!
14//! * [`Compact`]: A variant of the default formatter, optimized for
15//!   short line lengths. Fields from the current span context are appended to
16//!   the fields of the formatted event, and span names are not shown; the
17//!   verbosity level is abbreviated to a single character. See
18//!   [here](Compact#example-output) for sample output.
19//!
20//! * [`Pretty`]: Emits excessively pretty, multi-line logs, optimized
21//!   for human readability. This is primarily intended to be used in local
22//!   development and debugging, or for command-line applications, where
23//!   automated analysis and compact storage of logs is less of a priority than
24//!   readability and visual appeal. See [here](Pretty#example-output)
25//!   for sample output.
26//!
27//! * [`Json`]: Outputs newline-delimited JSON logs. This is intended
28//!   for production use with systems where structured logs are consumed as JSON
29//!   by analysis and viewing tools. The JSON output is not optimized for human
30//!   readability. See [here](Json#example-output) for sample output.
31use super::time::{FormatTime, SystemTime};
32use crate::{
33    field::{MakeOutput, MakeVisitor, RecordFields, VisitFmt, VisitOutput},
34    fmt::fmt_subscriber::{FmtContext, FormattedFields},
35    registry::LookupSpan,
36    registry::Scope,
37};
38
39use std::{fmt, marker::PhantomData};
40use tracing_core::{
41    field::{self, Field, Visit},
42    span, Collect, Event, Level,
43};
44
45#[cfg(feature = "tracing-log")]
46use tracing_log::NormalizeEvent;
47
48#[cfg(feature = "ansi")]
49use nu_ansi_term::{Color, Style};
50
51#[cfg(feature = "json")]
52mod json;
53#[cfg(feature = "json")]
54#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
55pub use json::*;
56
57#[cfg(feature = "ansi")]
58mod pretty;
59#[cfg(feature = "ansi")]
60#[cfg_attr(docsrs, doc(cfg(feature = "ansi")))]
61pub use pretty::*;
62
63use fmt::{Debug, Display};
64
65/// A type that can format a tracing [`Event`] to a [`Writer`].
66///
67/// `FormatEvent` is primarily used in the context of [`fmt::Collector`] or
68/// [`fmt::Subscriber`]. Each time an event is dispatched to [`fmt::Collector`]
69/// or [`fmt::Subscriber`], the collector or subscriber forwards it to its
70/// associated `FormatEvent` to emit a log message.
71///
72/// This trait is already implemented for function pointers with the same
73/// signature as `format_event`.
74///
75/// # Arguments
76///
77/// The following arguments are passed to `FormatEvent::format_event`:
78///
79/// * A [`FmtContext`]. This is an extension of the [`subscribe::Context`] type,
80///   which can be used for accessing stored information such as the current
81///   span context an event occurred in.
82///
83///   In addition, [`FmtContext`] exposes access to the [`FormatFields`]
84///   implementation that the subscriber was configured to use via the
85///   [`FmtContext::field_format`] method. This can be used when the
86///   [`FormatEvent`] implementation needs to format the event's fields.
87///
88///   For convenience, [`FmtContext`] also [implements `FormatFields`],
89///   forwarding to the configured [`FormatFields`] type.
90///
91/// * A [`Writer`] to which the formatted representation of the event is
92///   written. This type implements the [`std::fmt::Write`] trait, and therefore
93///   can be used with the [`std::write!`] and [`std::writeln!`] macros, as well
94///   as calling [`std::fmt::Write`] methods directly.
95///
96///   The [`Writer`] type also implements additional methods that provide
97///   information about how the event should be formatted. The
98///   [`Writer::has_ansi_escapes`] method indicates whether [ANSI terminal
99///   escape codes] are supported by the underlying I/O writer that the event
100///   will be written to. If this returns `true`, the formatter is permitted to
101///   use ANSI escape codes to add colors and other text formatting to its
102///   output. If it returns `false`, the event will be written to an output that
103///   does not support ANSI escape codes (such as a log file), and they should
104///   not be emitted.
105///
106///   Crates like [`nu_ansi_term`] and [`owo-colors`] can be used to add ANSI
107///   escape codes to formatted output.
108///
109/// * The actual [`Event`] to be formatted.
110///
111/// # Examples
112///
113/// This example re-implements a simiplified version of this crate's [default
114/// formatter]:
115///
116/// ```rust
117/// use std::fmt;
118/// use tracing_core::{Collect, Event};
119/// use tracing_subscriber::fmt::{
120///     format::{self, FormatEvent, FormatFields},
121///     FmtContext,
122///     FormattedFields,
123/// };
124/// use tracing_subscriber::registry::LookupSpan;
125///
126/// struct MyFormatter;
127///
128/// impl<C, N> FormatEvent<C, N> for MyFormatter
129/// where
130///     C: Collect + for<'a> LookupSpan<'a>,
131///     N: for<'a> FormatFields<'a> + 'static,
132/// {
133///     fn format_event(
134///         &self,
135///         ctx: &FmtContext<'_, C, N>,
136///         mut writer: format::Writer<'_>,
137///         event: &Event<'_>,
138///     ) -> fmt::Result {
139///         // Format values from the event's's metadata:
140///         let metadata = event.metadata();
141///         write!(&mut writer, "{} {}: ", metadata.level(), metadata.target())?;
142///
143///         // Format all the spans in the event's span context.
144///         if let Some(scope) = ctx.event_scope() {
145///             for span in scope.from_root() {
146///                 write!(writer, "{}", span.name())?;
147///
148///                 // `FormattedFields` is a formatted representation of the span's
149///                 // fields, which is stored in its extensions by the `fmt` layer's
150///                 // `new_span` method. The fields will have been formatted
151///                 // by the same field formatter that's provided to the event
152///                 // formatter in the `FmtContext`.
153///                 let ext = span.extensions();
154///                 let fields = &ext
155///                     .get::<FormattedFields<N>>()
156///                     .expect("will never be `None`");
157///
158///                 // Skip formatting the fields if the span had no fields.
159///                 if !fields.is_empty() {
160///                     write!(writer, "{{{}}}", fields)?;
161///                 }
162///                 write!(writer, ": ")?;
163///             }
164///         }
165///
166///         // Write fields on the event
167///         ctx.field_format().format_fields(writer.by_ref(), event)?;
168///
169///         writeln!(writer)
170///     }
171/// }
172///
173/// let _subscriber = tracing_subscriber::fmt()
174///     .event_format(MyFormatter)
175///     .init();
176///
177/// let _span = tracing::info_span!("my_span", answer = 42).entered();
178/// tracing::info!(question = "life, the universe, and everything", "hello world");
179/// ```
180///
181/// This formatter will print events like this:
182///
183/// ```text
184/// DEBUG yak_shaving::shaver: some-span{field-on-span=foo}: started shaving yak
185/// ```
186///
187/// [`fmt::Collector`]: super::Collector
188/// [`fmt::Subscriber`]: super::Subscriber
189/// [`subscribe::Context`]: crate::subscribe::Context
190/// [`Event`]: tracing::Event
191/// [implements `FormatFields`]: super::FmtContext#impl-FormatFields<'writer>
192/// [ANSI terminal escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
193/// [`Writer::has_ansi_escapes`]: Writer::has_ansi_escapes
194/// [`nu_ansi_term`]: https://crates.io/crates/nu_ansi_term
195/// [`owo-colors`]: https://crates.io/crates/owo-colors
196/// [default formatter]: Full
197pub trait FormatEvent<C, N>
198where
199    C: Collect + for<'a> LookupSpan<'a>,
200    N: for<'a> FormatFields<'a> + 'static,
201{
202    /// Write a log message for `Event` in `Context` to the given [`Writer`].
203    fn format_event(
204        &self,
205        ctx: &FmtContext<'_, C, N>,
206        writer: Writer<'_>,
207        event: &Event<'_>,
208    ) -> fmt::Result;
209}
210
211impl<C, N> FormatEvent<C, N>
212    for fn(ctx: &FmtContext<'_, C, N>, Writer<'_>, &Event<'_>) -> fmt::Result
213where
214    C: Collect + for<'a> LookupSpan<'a>,
215    N: for<'a> FormatFields<'a> + 'static,
216{
217    fn format_event(
218        &self,
219        ctx: &FmtContext<'_, C, N>,
220        writer: Writer<'_>,
221        event: &Event<'_>,
222    ) -> fmt::Result {
223        (*self)(ctx, writer, event)
224    }
225}
226/// A type that can format a [set of fields] to a [`Writer`].
227///
228/// `FormatFields` is primarily used in the context of [`fmt::Subscriber`]. Each
229/// time a span or event with fields is recorded, the subscriber will format
230/// those fields with its associated `FormatFields` implementation.
231///
232/// [set of fields]: RecordFields
233/// [`fmt::Subscriber`]: super::Subscriber
234pub trait FormatFields<'writer> {
235    /// Format the provided `fields` to the provided [`Writer`], returning a result.
236    fn format_fields<R: RecordFields>(&self, writer: Writer<'writer>, fields: R) -> fmt::Result;
237
238    /// Record additional field(s) on an existing span.
239    ///
240    /// By default, this appends a space to the current set of fields if it is
241    /// non-empty, and then calls `self.format_fields`. If different behavior is
242    /// required, the default implementation of this method can be overridden.
243    fn add_fields(
244        &self,
245        current: &'writer mut FormattedFields<Self>,
246        fields: &span::Record<'_>,
247    ) -> fmt::Result {
248        if !current.fields.is_empty() {
249            current.fields.push(' ');
250        }
251        self.format_fields(current.as_writer(), fields)
252    }
253}
254
255/// Returns the default configuration for an [event formatter].
256///
257/// Methods on the returned event formatter can be used for further
258/// configuration. For example:
259///
260/// ```rust
261/// let format = tracing_subscriber::fmt::format()
262///     .without_time()         // Don't include timestamps
263///     .with_target(false)     // Don't include event targets.
264///     .with_level(false)      // Don't include event levels.
265///     .compact();             // Use a more compact, abbreviated format.
266///
267/// // Use the configured formatter when building a new subscriber.
268/// tracing_subscriber::fmt()
269///     .event_format(format)
270///     .init();
271/// ```
272/// [event formatter]: FormatEvent
273pub fn format() -> Format {
274    Format::default()
275}
276
277/// Returns the default configuration for a JSON [event formatter].
278///
279/// [event formatter]: FormatEvent
280#[cfg(feature = "json")]
281#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
282pub fn json() -> Format<Json> {
283    format().json()
284}
285
286/// Returns a [`FormatFields`] implementation that formats fields using the
287/// provided function or closure.
288///
289pub fn debug_fn<F>(f: F) -> FieldFn<F>
290where
291    F: Fn(&mut Writer<'_>, &Field, &dyn fmt::Debug) -> fmt::Result + Clone,
292{
293    FieldFn(f)
294}
295
296/// A writer to which formatted representations of spans and events are written.
297///
298/// This type is provided as input to the [`FormatEvent::format_event`] and
299/// [`FormatFields::format_fields`] methods, which will write formatted
300/// representations of [`Event`]s and [fields] to the `Writer`.
301///
302/// This type implements the [`std::fmt::Write`] trait, allowing it to be used
303/// with any function that takes an instance of [`std::fmt::Write`].
304/// Additionally, it can be used with the standard library's [`std::write!`] and
305/// [`std::writeln!`] macros.
306///
307/// Additionally, a `Writer` may expose additional `tracing`-specific
308/// information to the formatter implementation.
309///
310/// [fields]: tracing_core::field
311pub struct Writer<'writer> {
312    writer: &'writer mut dyn fmt::Write,
313    // TODO(eliza): add ANSI support
314    is_ansi: bool,
315}
316
317/// A [`FormatFields`] implementation that formats fields by calling a function
318/// or closure.
319///
320#[derive(Debug, Clone)]
321pub struct FieldFn<F>(F);
322/// The [visitor] produced by [`FieldFn`]'s [`MakeVisitor`] implementation.
323///
324/// [visitor]: super::super::field::Visit
325/// [`MakeVisitor`]: super::super::field::MakeVisitor
326pub struct FieldFnVisitor<'a, F> {
327    f: F,
328    writer: Writer<'a>,
329    result: fmt::Result,
330}
331/// Marker for [`Format`] that indicates that the compact log format should be used.
332///
333/// The compact format includes fields from all currently entered spans, after
334/// the event's fields. Span fields are ordered (but not grouped) grouped by
335/// span, and span names are  not shown.A more compact representation of the
336/// event's [`Level`] is used, and additional information, such as the event's
337/// target, is disabled by default (but can be enabled explicitly).
338///
339/// # Example Output
340///
341/// <pre><font color="#4E9A06"><b>:;</b></font> <font color="#4E9A06">cargo</font> run --example fmt-compact
342/// <font color="#4E9A06"><b>    Finished</b></font> dev [unoptimized + debuginfo] target(s) in 0.08s
343/// <font color="#4E9A06"><b>     Running</b></font> `target/debug/examples/fmt-compact`
344/// <font color="#AAAAAA">2022-02-15T18:43:54.579731Z </font><font color="#4E9A06">i</font> preparing to shave yaks <i>number_of_yaks</i><font color="#AAAAAA">=3</font>
345/// <font color="#AAAAAA">2022-02-15T18:43:54.579802Z </font><font color="#4E9A06">i</font> shaving yaks <font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3</font>
346/// <font color="#AAAAAA">2022-02-15T18:43:54.579836Z </font><font color="#75507B">.</font> hello! I&apos;m gonna shave a yak <i>excitement</i><font color="#AAAAAA">=&quot;yay!&quot; </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3 </font><font color="#AAAAAA"><i>yak</i></font><font color="#AAAAAA">=1</font>
347/// <font color="#AAAAAA">2022-02-15T18:43:54.579861Z </font><font color="#75507B">.</font> yak shaved successfully <font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3 </font><font color="#AAAAAA"><i>yak</i></font><font color="#AAAAAA">=1</font>
348/// <font color="#AAAAAA">2022-02-15T18:43:54.579887Z </font><font color="#3465A4">:</font> <i>yak</i><font color="#AAAAAA">=1 </font><i>shaved</i><font color="#AAAAAA">=true </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3</font>
349/// <font color="#AAAAAA">2022-02-15T18:43:54.579904Z </font><font color="#75507B">.</font> <i>yaks_shaved</i><font color="#AAAAAA">=1 </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3</font>
350/// <font color="#AAAAAA">2022-02-15T18:43:54.579926Z </font><font color="#75507B">.</font> hello! I&apos;m gonna shave a yak <i>excitement</i><font color="#AAAAAA">=&quot;yay!&quot; </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3 </font><font color="#AAAAAA"><i>yak</i></font><font color="#AAAAAA">=2</font>
351/// <font color="#AAAAAA">2022-02-15T18:43:54.579941Z </font><font color="#75507B">.</font> yak shaved successfully <font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3 </font><font color="#AAAAAA"><i>yak</i></font><font color="#AAAAAA">=2</font>
352/// <font color="#AAAAAA">2022-02-15T18:43:54.579959Z </font><font color="#3465A4">:</font> <i>yak</i><font color="#AAAAAA">=2 </font><i>shaved</i><font color="#AAAAAA">=true </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3</font>
353/// <font color="#AAAAAA">2022-02-15T18:43:54.579973Z </font><font color="#75507B">.</font> <i>yaks_shaved</i><font color="#AAAAAA">=2 </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3</font>
354/// <font color="#AAAAAA">2022-02-15T18:43:54.579994Z </font><font color="#75507B">.</font> hello! I&apos;m gonna shave a yak <i>excitement</i><font color="#AAAAAA">=&quot;yay!&quot; </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3 </font><font color="#AAAAAA"><i>yak</i></font><font color="#AAAAAA">=3</font>
355/// <font color="#AAAAAA">2022-02-15T18:43:54.580013Z </font><font color="#C4A000">!</font> could not locate yak <font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3 </font><font color="#AAAAAA"><i>yak</i></font><font color="#AAAAAA">=3</font>
356/// <font color="#AAAAAA">2022-02-15T18:43:54.580032Z </font><font color="#3465A4">:</font> <i>yak</i><font color="#AAAAAA">=3 </font><i>shaved</i><font color="#AAAAAA">=false </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3</font>
357/// <font color="#AAAAAA">2022-02-15T18:43:54.580050Z </font><font color="#CC0000">X</font> failed to shave yak <i>yak</i><font color="#AAAAAA">=3 </font><i>error</i><font color="#AAAAAA">=missing yak </font><i>error.sources</i><font color="#AAAAAA">=[out of space, out of cash] </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3</font>
358/// <font color="#AAAAAA">2022-02-15T18:43:54.580067Z </font><font color="#75507B">.</font> <i>yaks_shaved</i><font color="#AAAAAA">=2 </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3</font>
359/// <font color="#AAAAAA">2022-02-15T18:43:54.580085Z </font><font color="#4E9A06">i</font> yak shaving completed <i>all_yaks_shaved</i><font color="#AAAAAA">=false</font>
360/// </pre>
361#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
362pub struct Compact;
363
364/// Marker for [`Format`] that indicates that the default log format should be used.
365///
366/// This formatter shows the span context before printing event data. Spans are
367/// displayed including their names and fields.
368///
369/// # Example Output
370///
371/// <pre><font color="#4E9A06"><b>:;</b></font> <font color="#4E9A06">cargo</font> run --example fmt
372/// <font color="#4E9A06"><b>    Finished</b></font> dev [unoptimized + debuginfo] target(s) in 0.08s
373/// <font color="#4E9A06"><b>     Running</b></font> `target/debug/examples/fmt`
374/// <font color="#AAAAAA">2022-02-15T18:40:14.289898Z </font><font color="#4E9A06"> INFO</font> fmt: preparing to shave yaks <i>number_of_yaks</i><font color="#AAAAAA">=3</font>
375/// <font color="#AAAAAA">2022-02-15T18:40:14.289974Z </font><font color="#4E9A06"> INFO</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: shaving yaks</font>
376/// <font color="#AAAAAA">2022-02-15T18:40:14.290011Z </font><font color="#75507B">TRACE</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">:</font><b>shave{</b><i>yak</i><font color="#AAAAAA">=1</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: hello! I&apos;m gonna shave a yak </font><i>excitement</i><font color="#AAAAAA">=&quot;yay!&quot;</font>
377/// <font color="#AAAAAA">2022-02-15T18:40:14.290038Z </font><font color="#75507B">TRACE</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">:</font><b>shave{</b><i>yak</i><font color="#AAAAAA">=1</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: yak shaved successfully</font>
378/// <font color="#AAAAAA">2022-02-15T18:40:14.290070Z </font><font color="#3465A4">DEBUG</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">: yak_events: </font><i>yak</i><font color="#AAAAAA">=1 </font><i>shaved</i><font color="#AAAAAA">=true</font>
379/// <font color="#AAAAAA">2022-02-15T18:40:14.290089Z </font><font color="#75507B">TRACE</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: </font><i>yaks_shaved</i><font color="#AAAAAA">=1</font>
380/// <font color="#AAAAAA">2022-02-15T18:40:14.290114Z </font><font color="#75507B">TRACE</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">:</font><b>shave{</b><i>yak</i><font color="#AAAAAA">=2</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: hello! I&apos;m gonna shave a yak </font><i>excitement</i><font color="#AAAAAA">=&quot;yay!&quot;</font>
381/// <font color="#AAAAAA">2022-02-15T18:40:14.290134Z </font><font color="#75507B">TRACE</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">:</font><b>shave{</b><i>yak</i><font color="#AAAAAA">=2</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: yak shaved successfully</font>
382/// <font color="#AAAAAA">2022-02-15T18:40:14.290157Z </font><font color="#3465A4">DEBUG</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">: yak_events: </font><i>yak</i><font color="#AAAAAA">=2 </font><i>shaved</i><font color="#AAAAAA">=true</font>
383/// <font color="#AAAAAA">2022-02-15T18:40:14.290174Z </font><font color="#75507B">TRACE</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: </font><i>yaks_shaved</i><font color="#AAAAAA">=2</font>
384/// <font color="#AAAAAA">2022-02-15T18:40:14.290198Z </font><font color="#75507B">TRACE</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">:</font><b>shave{</b><i>yak</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: hello! I&apos;m gonna shave a yak </font><i>excitement</i><font color="#AAAAAA">=&quot;yay!&quot;</font>
385/// <font color="#AAAAAA">2022-02-15T18:40:14.290222Z </font><font color="#C4A000"> WARN</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">:</font><b>shave{</b><i>yak</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: could not locate yak</font>
386/// <font color="#AAAAAA">2022-02-15T18:40:14.290247Z </font><font color="#3465A4">DEBUG</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">: yak_events: </font><i>yak</i><font color="#AAAAAA">=3 </font><i>shaved</i><font color="#AAAAAA">=false</font>
387/// <font color="#AAAAAA">2022-02-15T18:40:14.290268Z </font><font color="#CC0000">ERROR</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: failed to shave yak </font><i>yak</i><font color="#AAAAAA">=3 </font><i>error</i><font color="#AAAAAA">=missing yak </font><i>error.sources</i><font color="#AAAAAA">=[out of space, out of cash]</font>
388/// <font color="#AAAAAA">2022-02-15T18:40:14.290287Z </font><font color="#75507B">TRACE</font> <b>shaving_yaks{</b><i>yaks</i><font color="#AAAAAA">=3</font><b>}</b><font color="#AAAAAA">: fmt::yak_shave: </font><i>yaks_shaved</i><font color="#AAAAAA">=2</font>
389/// <font color="#AAAAAA">2022-02-15T18:40:14.290309Z </font><font color="#4E9A06"> INFO</font> fmt: yak shaving completed. <i>all_yaks_shaved</i><font color="#AAAAAA">=false</font>
390/// </pre>
391#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
392pub struct Full;
393
394/// A pre-configured event formatter.
395///
396/// You will usually want to use this as the `FormatEvent` for a `FmtSubscriber`.
397///
398/// The default logging format, [`Full`] includes all fields in each event and its containing
399/// spans. The [`Compact`] logging format is intended to produce shorter log
400/// lines; it displays each event's fields, along with fields from the current
401/// span context, but other information is abbreviated. The [`Pretty`] logging
402/// format is an extra-verbose, multi-line human-readable logging format
403/// intended for use in development.
404#[derive(Debug, Clone)]
405pub struct Format<F = Full, T = SystemTime> {
406    format: F,
407    pub(crate) timer: T,
408    pub(crate) ansi: Option<bool>,
409    pub(crate) display_timestamp: bool,
410    pub(crate) display_target: bool,
411    pub(crate) display_level: bool,
412    pub(crate) display_thread_id: bool,
413    pub(crate) display_thread_name: bool,
414    pub(crate) display_filename: bool,
415    pub(crate) display_line_number: bool,
416}
417
418// === impl Writer ===
419
420impl<'writer> Writer<'writer> {
421    // TODO(eliza): consider making this a public API?
422    // We may not want to do that if we choose to expose specialized
423    // constructors instead (e.g. `from_string` that stores whether the string
424    // is empty...?)
425    //(@kaifastromai) I suppose having dedicated constructors may have certain benefits
426    // but I am not privy to the larger direction of tracing/subscriber.
427    /// Create a new [`Writer`] from any type that implements [`fmt::Write`].
428    ///
429    /// The returned `Writer` value may be passed as an argument to methods
430    /// such as [`Format::format_event`]. Since constructing a `Writer`
431    /// mutably borrows the underlying [`fmt::Write`] instance, that value may
432    /// be accessed again once the `Writer` is dropped. For example, if the
433    /// value implementing [`fmt::Write`] is a [`String`], it will contain
434    /// the formatted output of [`Format::format_event`], which may then be
435    /// used for other purposes.
436    #[must_use]
437    pub fn new(writer: &'writer mut impl fmt::Write) -> Self {
438        Self {
439            writer: writer as &mut dyn fmt::Write,
440            is_ansi: false,
441        }
442    }
443
444    // TODO(eliza): consider making this a public API?
445    pub(crate) fn with_ansi(self, is_ansi: bool) -> Self {
446        Self { is_ansi, ..self }
447    }
448
449    /// Return a new `Writer` that mutably borrows `self`.
450    ///
451    /// This can be used to temporarily borrow a `Writer` to pass a new `Writer`
452    /// to a function that takes a `Writer` by value, allowing the original writer
453    /// to still be used once that function returns.
454    pub fn by_ref(&mut self) -> Writer<'_> {
455        let is_ansi = self.is_ansi;
456        Writer {
457            writer: self as &mut dyn fmt::Write,
458            is_ansi,
459        }
460    }
461
462    /// Writes a string slice into this `Writer`, returning whether the write succeeded.
463    ///
464    /// This method can only succeed if the entire string slice was successfully
465    /// written, and this method will not return until all data has been written
466    /// or an error occurs.
467    ///
468    /// This is identical to calling the [`write_str` method] from the `Writer`'s
469    /// [`std::fmt::Write`] implementation. However, it is also provided as an
470    /// inherent method, so that `Writer`s can be used without needing to import the
471    /// [`std::fmt::Write`] trait.
472    ///
473    /// # Errors
474    ///
475    /// This function will return an instance of [`std::fmt::Error`] on error.
476    ///
477    /// [`write_str` method]: std::fmt::Write::write_str
478    #[inline]
479    pub fn write_str(&mut self, s: &str) -> fmt::Result {
480        self.writer.write_str(s)
481    }
482
483    /// Writes a [`char`] into this writer, returning whether the write succeeded.
484    ///
485    /// A single [`char`] may be encoded as more than one byte.
486    /// This method can only succeed if the entire byte sequence was successfully
487    /// written, and this method will not return until all data has been
488    /// written or an error occurs.
489    ///
490    /// This is identical to calling the [`write_char` method] from the `Writer`'s
491    /// [`std::fmt::Write`] implementation. However, it is also provided as an
492    /// inherent method, so that `Writer`s can be used without needing to import the
493    /// [`std::fmt::Write`] trait.
494    ///
495    /// # Errors
496    ///
497    /// This function will return an instance of [`std::fmt::Error`] on error.
498    ///
499    /// [`write_char` method]: std::fmt::Write::write_char
500    #[inline]
501    pub fn write_char(&mut self, c: char) -> fmt::Result {
502        self.writer.write_char(c)
503    }
504
505    /// Glue for usage of the [`write!`] macro with `Writer`s.
506    ///
507    /// This method should generally not be invoked manually, but rather through
508    /// the [`write!`] macro itself.
509    ///
510    /// This is identical to calling the [`write_fmt` method] from the `Writer`'s
511    /// [`std::fmt::Write`] implementation. However, it is also provided as an
512    /// inherent method, so that `Writer`s can be used with the [`write!` macro]
513    /// without needing to import the
514    /// [`std::fmt::Write`] trait.
515    ///
516    /// [`write_fmt` method]: std::fmt::Write::write_fmt
517    pub fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
518        self.writer.write_fmt(args)
519    }
520
521    /// Returns `true` if [ANSI escape codes] may be used to add colors
522    /// and other formatting when writing to this `Writer`.
523    ///
524    /// If this returns `false`, formatters should not emit ANSI escape codes.
525    ///
526    /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
527    pub fn has_ansi_escapes(&self) -> bool {
528        self.is_ansi
529    }
530
531    pub(in crate::fmt::format) fn bold(&self) -> Style {
532        #[cfg(feature = "ansi")]
533        {
534            if self.is_ansi {
535                return Style::new().bold();
536            }
537        }
538
539        Style::new()
540    }
541
542    pub(in crate::fmt::format) fn dimmed(&self) -> Style {
543        #[cfg(feature = "ansi")]
544        {
545            if self.is_ansi {
546                return Style::new().dimmed();
547            }
548        }
549
550        Style::new()
551    }
552
553    pub(in crate::fmt::format) fn italic(&self) -> Style {
554        #[cfg(feature = "ansi")]
555        {
556            if self.is_ansi {
557                return Style::new().italic();
558            }
559        }
560
561        Style::new()
562    }
563}
564
565impl fmt::Write for Writer<'_> {
566    #[inline]
567    fn write_str(&mut self, s: &str) -> fmt::Result {
568        Writer::write_str(self, s)
569    }
570
571    #[inline]
572    fn write_char(&mut self, c: char) -> fmt::Result {
573        Writer::write_char(self, c)
574    }
575
576    #[inline]
577    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
578        Writer::write_fmt(self, args)
579    }
580}
581
582impl fmt::Debug for Writer<'_> {
583    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584        f.debug_struct("Writer")
585            .field("writer", &format_args!("<&mut dyn fmt::Write>"))
586            .field("is_ansi", &self.is_ansi)
587            .finish()
588    }
589}
590
591// === impl Format ===
592
593impl Default for Format<Full, SystemTime> {
594    fn default() -> Self {
595        Format {
596            format: Full,
597            timer: SystemTime,
598            ansi: None,
599            display_timestamp: true,
600            display_target: true,
601            display_level: true,
602            display_thread_id: false,
603            display_thread_name: false,
604            display_filename: false,
605            display_line_number: false,
606        }
607    }
608}
609
610impl<F, T> Format<F, T> {
611    /// Use a less verbose output format.
612    ///
613    /// See [`Compact`].
614    pub fn compact(self) -> Format<Compact, T> {
615        Format {
616            format: Compact,
617            timer: self.timer,
618            ansi: self.ansi,
619            display_target: false,
620            display_timestamp: self.display_timestamp,
621            display_level: self.display_level,
622            display_thread_id: self.display_thread_id,
623            display_thread_name: self.display_thread_name,
624            display_filename: self.display_filename,
625            display_line_number: self.display_line_number,
626        }
627    }
628
629    /// Use an excessively pretty, human-readable output format.
630    ///
631    /// See [`Pretty`].
632    ///
633    /// Note that this requires the "ansi" feature to be enabled.
634    ///
635    /// # Options
636    ///
637    /// [`Format::with_ansi`] can be used to disable ANSI terminal escape codes (which enable
638    /// formatting such as colors, bold, italic, etc) in event formatting. However, a field
639    /// formatter must be manually provided to avoid ANSI in the formatting of parent spans, like
640    /// so:
641    ///
642    /// ```
643    /// # use tracing_subscriber::fmt::format;
644    /// tracing_subscriber::fmt()
645    ///    .pretty()
646    ///    .with_ansi(false)
647    ///    .fmt_fields(format::PrettyFields::new().with_ansi(false))
648    ///    // ... other settings ...
649    ///    .init();
650    /// ```
651    #[cfg(feature = "ansi")]
652    #[cfg_attr(docsrs, doc(cfg(feature = "ansi")))]
653    pub fn pretty(self) -> Format<Pretty, T> {
654        Format {
655            format: Pretty::default(),
656            timer: self.timer,
657            ansi: self.ansi,
658            display_target: self.display_target,
659            display_timestamp: self.display_timestamp,
660            display_level: self.display_level,
661            display_thread_id: self.display_thread_id,
662            display_thread_name: self.display_thread_name,
663            display_filename: true,
664            display_line_number: true,
665        }
666    }
667
668    /// Use the full JSON format.
669    ///
670    /// The full format includes fields from all entered spans.
671    ///
672    /// # Example Output
673    ///
674    /// ```ignore,json
675    /// {"timestamp":"Feb 20 11:28:15.096","level":"INFO","target":"mycrate","fields":{"message":"some message", "key": "value"}}
676    /// ```
677    ///
678    /// # Options
679    ///
680    /// - [`Format::flatten_event`] can be used to enable flattening event fields into the root
681    ///   object.
682    #[cfg(feature = "json")]
683    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
684    pub fn json(self) -> Format<Json, T> {
685        Format {
686            format: Json::default(),
687            timer: self.timer,
688            ansi: self.ansi,
689            display_target: self.display_target,
690            display_timestamp: self.display_timestamp,
691            display_level: self.display_level,
692            display_thread_id: self.display_thread_id,
693            display_thread_name: self.display_thread_name,
694            display_filename: self.display_filename,
695            display_line_number: self.display_line_number,
696        }
697    }
698
699    /// Use the given [`timer`] for log message timestamps.
700    ///
701    /// See [`time` module] for the provided timer implementations.
702    ///
703    /// Note that using the `"time"` feature flag enables the
704    /// additional time formatters [`UtcTime`] and [`LocalTime`], which use the
705    /// [`time` crate] to provide more sophisticated timestamp formatting
706    /// options.
707    ///
708    /// [`timer`]: super::time::FormatTime
709    /// [`time` module]: mod@super::time
710    /// [`UtcTime`]: super::time::UtcTime
711    /// [`LocalTime`]: super::time::LocalTime
712    /// [`time` crate]: https://docs.rs/time/0.3
713    pub fn with_timer<T2>(self, timer: T2) -> Format<F, T2> {
714        Format {
715            format: self.format,
716            timer,
717            ansi: self.ansi,
718            display_target: self.display_target,
719            display_timestamp: self.display_timestamp,
720            display_level: self.display_level,
721            display_thread_id: self.display_thread_id,
722            display_thread_name: self.display_thread_name,
723            display_filename: self.display_filename,
724            display_line_number: self.display_line_number,
725        }
726    }
727
728    /// Do not emit timestamps with log messages.
729    pub fn without_time(self) -> Format<F, ()> {
730        Format {
731            format: self.format,
732            timer: (),
733            ansi: self.ansi,
734            display_timestamp: false,
735            display_target: self.display_target,
736            display_level: self.display_level,
737            display_thread_id: self.display_thread_id,
738            display_thread_name: self.display_thread_name,
739            display_filename: self.display_filename,
740            display_line_number: self.display_line_number,
741        }
742    }
743
744    /// Enable ANSI terminal colors for formatted output.
745    pub fn with_ansi(self, ansi: bool) -> Format<F, T> {
746        Format {
747            ansi: Some(ansi),
748            ..self
749        }
750    }
751
752    /// Sets whether or not an event's target is displayed.
753    pub fn with_target(self, display_target: bool) -> Format<F, T> {
754        Format {
755            display_target,
756            ..self
757        }
758    }
759
760    /// Sets whether or not an event's level is displayed.
761    pub fn with_level(self, display_level: bool) -> Format<F, T> {
762        Format {
763            display_level,
764            ..self
765        }
766    }
767
768    /// Sets whether or not the [thread ID] of the current thread is displayed
769    /// when formatting events.
770    ///
771    /// [thread ID]: std::thread::ThreadId
772    pub fn with_thread_ids(self, display_thread_id: bool) -> Format<F, T> {
773        Format {
774            display_thread_id,
775            ..self
776        }
777    }
778
779    /// Sets whether or not the [name] of the current thread is displayed
780    /// when formatting events.
781    ///
782    /// [name]: std::thread#naming-threads
783    pub fn with_thread_names(self, display_thread_name: bool) -> Format<F, T> {
784        Format {
785            display_thread_name,
786            ..self
787        }
788    }
789
790    /// Sets whether or not an event's [source code file path][file] is
791    /// displayed.
792    ///
793    /// [file]: tracing_core::Metadata::file
794    pub fn with_file(self, display_filename: bool) -> Format<F, T> {
795        Format {
796            display_filename,
797            ..self
798        }
799    }
800
801    /// Sets whether or not an event's [source code line number][line] is
802    /// displayed.
803    ///
804    /// [line]: tracing_core::Metadata::line
805    pub fn with_line_number(self, display_line_number: bool) -> Format<F, T> {
806        Format {
807            display_line_number,
808            ..self
809        }
810    }
811
812    /// Sets whether or not the source code location from which an event
813    /// originated is displayed.
814    ///
815    /// This is equivalent to calling [`Format::with_file`] and
816    /// [`Format::with_line_number`] with the same value.
817    pub fn with_source_location(self, display_location: bool) -> Self {
818        self.with_line_number(display_location)
819            .with_file(display_location)
820    }
821
822    fn format_level(&self, level: Level, writer: &mut Writer<'_>) -> fmt::Result
823    where
824        F: LevelNames,
825    {
826        if self.display_level {
827            let fmt_level = {
828                #[cfg(feature = "ansi")]
829                {
830                    F::format_level(level, writer.has_ansi_escapes())
831                }
832                #[cfg(not(feature = "ansi"))]
833                {
834                    F::format_level(level)
835                }
836            };
837            return write!(writer, "{} ", fmt_level);
838        }
839
840        Ok(())
841    }
842
843    #[inline]
844    fn format_timestamp(&self, writer: &mut Writer<'_>) -> fmt::Result
845    where
846        T: FormatTime,
847    {
848        // If timestamps are disabled, do nothing.
849        if !self.display_timestamp {
850            return Ok(());
851        }
852
853        // If ANSI color codes are enabled, format the timestamp with ANSI
854        // colors.
855        #[cfg(feature = "ansi")]
856        {
857            if writer.has_ansi_escapes() {
858                let style = Style::new().dimmed();
859                write!(writer, "{}", style.prefix())?;
860
861                // If getting the timestamp failed, don't bail --- only bail on
862                // formatting errors.
863                if self.timer.format_time(writer).is_err() {
864                    writer.write_str("<unknown time>")?;
865                }
866
867                write!(writer, "{} ", style.suffix())?;
868                return Ok(());
869            }
870        }
871
872        // Otherwise, just format the timestamp without ANSI formatting.
873        // If getting the timestamp failed, don't bail --- only bail on
874        // formatting errors.
875        if self.timer.format_time(writer).is_err() {
876            writer.write_str("<unknown time>")?;
877        }
878        writer.write_char(' ')
879    }
880}
881
882#[cfg(feature = "json")]
883#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
884impl<T> Format<Json, T> {
885    /// Use the full JSON format with the event's event fields flattened.
886    ///
887    /// # Example Output
888    ///
889    /// ```ignore,json
890    /// {"timestamp":"Feb 20 11:28:15.096","level":"INFO","target":"mycrate", "message":"some message", "key": "value"}
891    /// ```
892    /// See [`Json`]
893    #[cfg(feature = "json")]
894    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
895    pub fn flatten_event(mut self, flatten_event: bool) -> Format<Json, T> {
896        self.format.flatten_event(flatten_event);
897        self
898    }
899
900    /// Sets whether or not the formatter will include the current span in
901    /// formatted events.
902    ///
903    /// See [`Json`]
904    #[cfg(feature = "json")]
905    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
906    pub fn with_current_span(mut self, display_current_span: bool) -> Format<Json, T> {
907        self.format.with_current_span(display_current_span);
908        self
909    }
910
911    /// Sets whether or not the formatter will include a list (from root to
912    /// leaf) of all currently entered spans in formatted events.
913    ///
914    /// See [`Json`]
915    #[cfg(feature = "json")]
916    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
917    pub fn with_span_list(mut self, display_span_list: bool) -> Format<Json, T> {
918        self.format.with_span_list(display_span_list);
919        self
920    }
921}
922
923impl<C, N, T> FormatEvent<C, N> for Format<Full, T>
924where
925    C: Collect + for<'a> LookupSpan<'a>,
926    N: for<'a> FormatFields<'a> + 'static,
927    T: FormatTime,
928{
929    fn format_event(
930        &self,
931        ctx: &FmtContext<'_, C, N>,
932        mut writer: Writer<'_>,
933        event: &Event<'_>,
934    ) -> fmt::Result {
935        #[cfg(feature = "tracing-log")]
936        let normalized_meta = event.normalized_metadata();
937        #[cfg(feature = "tracing-log")]
938        let meta = normalized_meta.as_ref().unwrap_or_else(|| event.metadata());
939        #[cfg(not(feature = "tracing-log"))]
940        let meta = event.metadata();
941
942        // if the `Format` struct *also* has an ANSI color configuration,
943        // override the writer...the API for configuring ANSI color codes on the
944        // `Format` struct is deprecated, but we still need to honor those
945        // configurations.
946        if let Some(ansi) = self.ansi {
947            writer = writer.with_ansi(ansi);
948        }
949
950        self.format_timestamp(&mut writer)?;
951        self.format_level(*meta.level(), &mut writer)?;
952
953        if self.display_thread_name {
954            let current_thread = std::thread::current();
955            match current_thread.name() {
956                Some(name) => {
957                    write!(writer, "{} ", FmtThreadName::new(name))?;
958                }
959                // fall-back to thread id when name is absent and ids are not enabled
960                None if !self.display_thread_id => {
961                    write!(writer, "{:0>2?} ", current_thread.id())?;
962                }
963                _ => {}
964            }
965        }
966
967        if self.display_thread_id {
968            write!(writer, "{:0>2?} ", std::thread::current().id())?;
969        }
970
971        let dimmed = writer.dimmed();
972
973        if let Some(scope) = ctx.event_scope() {
974            let bold = writer.bold();
975
976            let mut seen = false;
977
978            for span in scope.from_root() {
979                write!(writer, "{}", bold.paint(span.metadata().name()))?;
980                seen = true;
981
982                let ext = span.extensions();
983                if let Some(fields) = &ext.get::<FormattedFields<N>>() {
984                    if !fields.is_empty() {
985                        write!(writer, "{}{}{}", bold.paint("{"), fields, bold.paint("}"))?;
986                    }
987                }
988                write!(writer, "{}", dimmed.paint(":"))?;
989            }
990
991            if seen {
992                writer.write_char(' ')?;
993            }
994        }
995
996        if self.display_target {
997            write!(
998                writer,
999                "{}{} ",
1000                dimmed.paint(meta.target()),
1001                dimmed.paint(":")
1002            )?;
1003        }
1004
1005        let line_number = if self.display_line_number {
1006            meta.line()
1007        } else {
1008            None
1009        };
1010
1011        if self.display_filename {
1012            if let Some(filename) = meta.file() {
1013                write!(
1014                    writer,
1015                    "{}{}{}",
1016                    dimmed.paint(filename),
1017                    dimmed.paint(":"),
1018                    if line_number.is_some() { "" } else { " " }
1019                )?;
1020            }
1021        }
1022
1023        if let Some(line_number) = line_number {
1024            write!(
1025                writer,
1026                "{}{}:{} ",
1027                dimmed.prefix(),
1028                line_number,
1029                dimmed.suffix()
1030            )?;
1031        }
1032
1033        ctx.format_fields(writer.by_ref(), event)?;
1034        writeln!(writer)
1035    }
1036}
1037
1038impl<C, N, T> FormatEvent<C, N> for Format<Compact, T>
1039where
1040    C: Collect + for<'a> LookupSpan<'a>,
1041    N: for<'a> FormatFields<'a> + 'static,
1042    T: FormatTime,
1043{
1044    fn format_event(
1045        &self,
1046        ctx: &FmtContext<'_, C, N>,
1047        mut writer: Writer<'_>,
1048        event: &Event<'_>,
1049    ) -> fmt::Result {
1050        #[cfg(feature = "tracing-log")]
1051        let normalized_meta = event.normalized_metadata();
1052        #[cfg(feature = "tracing-log")]
1053        let meta = normalized_meta.as_ref().unwrap_or_else(|| event.metadata());
1054        #[cfg(not(feature = "tracing-log"))]
1055        let meta = event.metadata();
1056
1057        self.format_timestamp(&mut writer)?;
1058        self.format_level(*meta.level(), &mut writer)?;
1059
1060        if self.display_thread_name {
1061            let current_thread = std::thread::current();
1062            match current_thread.name() {
1063                Some(name) => {
1064                    write!(writer, "{} ", FmtThreadName::new(name))?;
1065                }
1066                // fall-back to thread id when name is absent and ids are not enabled
1067                None if !self.display_thread_id => {
1068                    write!(writer, "{:0>2?} ", current_thread.id())?;
1069                }
1070                _ => {}
1071            }
1072        }
1073
1074        if self.display_thread_id {
1075            write!(writer, "{:0>2?} ", std::thread::current().id())?;
1076        }
1077
1078        let dimmed = writer.dimmed();
1079        if self.display_target {
1080            write!(
1081                writer,
1082                "{}{}",
1083                dimmed.paint(meta.target()),
1084                dimmed.paint(":")
1085            )?;
1086        }
1087
1088        if self.display_filename {
1089            if let Some(filename) = meta.file() {
1090                write!(writer, "{}{}", dimmed.paint(filename), dimmed.paint(":"))?;
1091            }
1092        }
1093
1094        if self.display_line_number {
1095            if let Some(line_number) = meta.line() {
1096                write!(
1097                    writer,
1098                    "{}{}{}{}",
1099                    dimmed.prefix(),
1100                    line_number,
1101                    dimmed.suffix(),
1102                    dimmed.paint(":")
1103                )?;
1104            }
1105        }
1106
1107        ctx.format_fields(writer.by_ref(), event)?;
1108
1109        for span in ctx.event_scope().into_iter().flat_map(Scope::from_root) {
1110            let exts = span.extensions();
1111            if let Some(fields) = exts.get::<FormattedFields<N>>() {
1112                if !fields.is_empty() {
1113                    write!(writer, " {}", dimmed.paint(&fields.fields))?;
1114                }
1115            }
1116        }
1117
1118        writeln!(writer)
1119    }
1120}
1121
1122// === impl FormatFields ===
1123impl<'writer, M> FormatFields<'writer> for M
1124where
1125    M: MakeOutput<Writer<'writer>, fmt::Result>,
1126    M::Visitor: VisitFmt + VisitOutput<fmt::Result>,
1127{
1128    fn format_fields<R: RecordFields>(&self, writer: Writer<'writer>, fields: R) -> fmt::Result {
1129        let mut v = self.make_visitor(writer);
1130        fields.record(&mut v);
1131        v.finish()
1132    }
1133}
1134
1135/// The default [`FormatFields`] implementation.
1136///
1137#[derive(Debug)]
1138pub struct DefaultFields {
1139    // reserve the ability to add fields to this without causing a breaking
1140    // change in the future.
1141    _private: (),
1142}
1143
1144/// The [visitor] produced by [`DefaultFields`]'s [`MakeVisitor`] implementation.
1145///
1146/// [visitor]: super::super::field::Visit
1147/// [`MakeVisitor`]: super::super::field::MakeVisitor
1148#[derive(Debug)]
1149pub struct DefaultVisitor<'a> {
1150    writer: Writer<'a>,
1151    is_empty: bool,
1152    result: fmt::Result,
1153}
1154
1155impl DefaultFields {
1156    /// Returns a new default [`FormatFields`] implementation.
1157    ///
1158    pub fn new() -> Self {
1159        Self { _private: () }
1160    }
1161}
1162
1163impl Default for DefaultFields {
1164    fn default() -> Self {
1165        Self::new()
1166    }
1167}
1168
1169impl<'a> MakeVisitor<Writer<'a>> for DefaultFields {
1170    type Visitor = DefaultVisitor<'a>;
1171
1172    #[inline]
1173    fn make_visitor(&self, target: Writer<'a>) -> Self::Visitor {
1174        DefaultVisitor::new(target, true)
1175    }
1176}
1177
1178// === impl DefaultVisitor ===
1179
1180impl<'a> DefaultVisitor<'a> {
1181    /// Returns a new default visitor that formats to the provided `writer`.
1182    ///
1183    /// # Arguments
1184    /// - `writer`: the writer to format to.
1185    /// - `is_empty`: whether or not any fields have been previously written to
1186    ///   that writer.
1187    pub fn new(writer: Writer<'a>, is_empty: bool) -> Self {
1188        Self {
1189            writer,
1190            is_empty,
1191            result: Ok(()),
1192        }
1193    }
1194
1195    fn maybe_pad(&mut self) {
1196        if self.is_empty {
1197            self.is_empty = false;
1198        } else {
1199            self.result = write!(self.writer, " ");
1200        }
1201    }
1202}
1203
1204impl field::Visit for DefaultVisitor<'_> {
1205    fn record_str(&mut self, field: &Field, value: &str) {
1206        if self.result.is_err() {
1207            return;
1208        }
1209
1210        if field.name() == "message" {
1211            self.record_debug(field, &format_args!("{}", value))
1212        } else {
1213            self.record_debug(field, &value)
1214        }
1215    }
1216
1217    fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
1218        if let Some(source) = value.source() {
1219            let italic = self.writer.italic();
1220            self.record_debug(
1221                field,
1222                &format_args!(
1223                    "{} {}{}{}{}",
1224                    value,
1225                    italic.paint(field.name()),
1226                    italic.paint(".sources"),
1227                    self.writer.dimmed().paint("="),
1228                    ErrorSourceList(source)
1229                ),
1230            )
1231        } else {
1232            self.record_debug(field, &format_args!("{}", value))
1233        }
1234    }
1235
1236    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
1237        if self.result.is_err() {
1238            return;
1239        }
1240
1241        let name = field.name();
1242
1243        // Skip fields that are actually log metadata that have already been handled
1244        #[cfg(feature = "tracing-log")]
1245        if name.starts_with("log.") {
1246            debug_assert_eq!(self.result, Ok(())); // no need to update self.result
1247            return;
1248        }
1249
1250        // emit separating spaces if needed
1251        self.maybe_pad();
1252
1253        self.result = match name {
1254            "message" => write!(self.writer, "{:?}", value),
1255            name if name.starts_with("r#") => write!(
1256                self.writer,
1257                "{}{}{:?}",
1258                self.writer.italic().paint(&name[2..]),
1259                self.writer.dimmed().paint("="),
1260                value
1261            ),
1262            name => write!(
1263                self.writer,
1264                "{}{}{:?}",
1265                self.writer.italic().paint(name),
1266                self.writer.dimmed().paint("="),
1267                value
1268            ),
1269        };
1270    }
1271}
1272
1273impl crate::field::VisitOutput<fmt::Result> for DefaultVisitor<'_> {
1274    fn finish(self) -> fmt::Result {
1275        self.result
1276    }
1277}
1278
1279impl crate::field::VisitFmt for DefaultVisitor<'_> {
1280    fn writer(&mut self) -> &mut dyn fmt::Write {
1281        &mut self.writer
1282    }
1283}
1284
1285/// Renders an error into a list of sources, *including* the error
1286struct ErrorSourceList<'a>(&'a (dyn std::error::Error + 'static));
1287
1288impl Display for ErrorSourceList<'_> {
1289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1290        let mut list = f.debug_list();
1291        let mut curr = Some(self.0);
1292        while let Some(curr_err) = curr {
1293            list.entry(&format_args!("{}", curr_err));
1294            curr = curr_err.source();
1295        }
1296        list.finish()
1297    }
1298}
1299
1300#[cfg(not(feature = "ansi"))]
1301struct Style;
1302
1303#[cfg(not(feature = "ansi"))]
1304impl Style {
1305    fn new() -> Self {
1306        Style
1307    }
1308
1309    fn paint(&self, d: impl fmt::Display) -> impl fmt::Display {
1310        d
1311    }
1312
1313    fn prefix(&self) -> impl fmt::Display {
1314        ""
1315    }
1316
1317    fn suffix(&self) -> impl fmt::Display {
1318        ""
1319    }
1320}
1321
1322struct FmtThreadName<'a> {
1323    name: &'a str,
1324}
1325
1326impl<'a> FmtThreadName<'a> {
1327    pub(crate) fn new(name: &'a str) -> Self {
1328        Self { name }
1329    }
1330}
1331
1332impl fmt::Display for FmtThreadName<'_> {
1333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1334        use std::sync::atomic::{
1335            AtomicUsize,
1336            Ordering::{AcqRel, Acquire, Relaxed},
1337        };
1338
1339        // Track the longest thread name length we've seen so far in an atomic,
1340        // so that it can be updated by any thread.
1341        static MAX_LEN: AtomicUsize = AtomicUsize::new(0);
1342        let len = self.name.len();
1343        // Snapshot the current max thread name length.
1344        let mut max_len = MAX_LEN.load(Relaxed);
1345
1346        while len > max_len {
1347            // Try to set a new max length, if it is still the value we took a
1348            // snapshot of.
1349            match MAX_LEN.compare_exchange(max_len, len, AcqRel, Acquire) {
1350                // We successfully set the new max value
1351                Ok(_) => break,
1352                // Another thread set a new max value since we last observed
1353                // it! It's possible that the new length is actually longer than
1354                // ours, so we'll loop again and check whether our length is
1355                // still the longest. If not, we'll just use the newer value.
1356                Err(actual) => max_len = actual,
1357            }
1358        }
1359
1360        // pad thread name using `max_len`
1361        write!(f, "{:>width$}", self.name, width = max_len)
1362    }
1363}
1364
1365trait LevelNames {
1366    const TRACE_STR: &'static str;
1367    const DEBUG_STR: &'static str;
1368    const INFO_STR: &'static str;
1369    const WARN_STR: &'static str;
1370    const ERROR_STR: &'static str;
1371
1372    #[cfg(feature = "ansi")]
1373    fn format_level(level: Level, ansi: bool) -> FmtLevel<Self> {
1374        FmtLevel {
1375            level,
1376            ansi,
1377            _f: PhantomData,
1378        }
1379    }
1380
1381    #[cfg(not(feature = "ansi"))]
1382    fn format_level(level: Level) -> FmtLevel<Self> {
1383        FmtLevel {
1384            level,
1385            _f: PhantomData,
1386        }
1387    }
1388}
1389
1390#[cfg(feature = "ansi")]
1391impl LevelNames for Pretty {
1392    const TRACE_STR: &'static str = "TRACE";
1393    const DEBUG_STR: &'static str = "DEBUG";
1394    const INFO_STR: &'static str = " INFO";
1395    const WARN_STR: &'static str = " WARN";
1396    const ERROR_STR: &'static str = "ERROR";
1397}
1398
1399impl LevelNames for Full {
1400    const TRACE_STR: &'static str = "TRACE";
1401    const DEBUG_STR: &'static str = "DEBUG";
1402    const INFO_STR: &'static str = " INFO";
1403    const WARN_STR: &'static str = " WARN";
1404    const ERROR_STR: &'static str = "ERROR";
1405}
1406impl LevelNames for Compact {
1407    const TRACE_STR: &'static str = ".";
1408    const DEBUG_STR: &'static str = ":";
1409    const INFO_STR: &'static str = "i";
1410    const WARN_STR: &'static str = "!";
1411    const ERROR_STR: &'static str = "X";
1412}
1413
1414struct FmtLevel<F: ?Sized> {
1415    level: Level,
1416    #[cfg(feature = "ansi")]
1417    ansi: bool,
1418    _f: PhantomData<fn(F)>,
1419}
1420
1421impl<F: LevelNames> fmt::Display for FmtLevel<F> {
1422    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1423        #[cfg(feature = "ansi")]
1424        {
1425            if self.ansi {
1426                return match self.level {
1427                    Level::TRACE => write!(f, "{}", Color::Purple.paint(F::TRACE_STR)),
1428                    Level::DEBUG => write!(f, "{}", Color::Blue.paint(F::DEBUG_STR)),
1429                    Level::INFO => write!(f, "{}", Color::Green.paint(F::INFO_STR)),
1430                    Level::WARN => write!(f, "{}", Color::Yellow.paint(F::WARN_STR)),
1431                    Level::ERROR => write!(f, "{}", Color::Red.paint(F::ERROR_STR)),
1432                };
1433            }
1434        }
1435
1436        match self.level {
1437            Level::TRACE => f.pad(F::TRACE_STR),
1438            Level::DEBUG => f.pad(F::DEBUG_STR),
1439            Level::INFO => f.pad(F::INFO_STR),
1440            Level::WARN => f.pad(F::WARN_STR),
1441            Level::ERROR => f.pad(F::ERROR_STR),
1442        }
1443    }
1444}
1445
1446// === impl FieldFn ===
1447
1448impl<'a, F> MakeVisitor<Writer<'a>> for FieldFn<F>
1449where
1450    F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result + Clone,
1451{
1452    type Visitor = FieldFnVisitor<'a, F>;
1453
1454    fn make_visitor(&self, writer: Writer<'a>) -> Self::Visitor {
1455        FieldFnVisitor {
1456            writer,
1457            f: self.0.clone(),
1458            result: Ok(()),
1459        }
1460    }
1461}
1462
1463impl<'a, F> Visit for FieldFnVisitor<'a, F>
1464where
1465    F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result,
1466{
1467    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
1468        if self.result.is_ok() {
1469            self.result = (self.f)(&mut self.writer, field, value)
1470        }
1471    }
1472}
1473
1474impl<'a, F> VisitOutput<fmt::Result> for FieldFnVisitor<'a, F>
1475where
1476    F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result,
1477{
1478    fn finish(self) -> fmt::Result {
1479        self.result
1480    }
1481}
1482
1483impl<'a, F> VisitFmt for FieldFnVisitor<'a, F>
1484where
1485    F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result,
1486{
1487    fn writer(&mut self) -> &mut dyn fmt::Write {
1488        &mut self.writer
1489    }
1490}
1491
1492impl<F> fmt::Debug for FieldFnVisitor<'_, F> {
1493    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1494        f.debug_struct("FieldFnVisitor")
1495            .field("f", &format_args!("{}", std::any::type_name::<F>()))
1496            .field("writer", &self.writer)
1497            .field("result", &self.result)
1498            .finish()
1499    }
1500}
1501
1502// === printing synthetic Span events ===
1503
1504/// Configures what points in the span lifecycle are logged as events.
1505///
1506/// See also [`with_span_events`](super::CollectorBuilder::with_span_events()).
1507#[derive(Clone, Eq, PartialEq, Ord, PartialOrd)]
1508pub struct FmtSpan(u8);
1509
1510impl FmtSpan {
1511    /// one event when span is created
1512    pub const NEW: FmtSpan = FmtSpan(1 << 0);
1513    /// one event per enter of a span
1514    pub const ENTER: FmtSpan = FmtSpan(1 << 1);
1515    /// one event per exit of a span
1516    pub const EXIT: FmtSpan = FmtSpan(1 << 2);
1517    /// one event when the span is dropped
1518    pub const CLOSE: FmtSpan = FmtSpan(1 << 3);
1519
1520    /// spans are ignored (this is the default)
1521    pub const NONE: FmtSpan = FmtSpan(0);
1522    /// one event per enter/exit of a span
1523    pub const ACTIVE: FmtSpan = FmtSpan(FmtSpan::ENTER.0 | FmtSpan::EXIT.0);
1524    /// events at all points (new, enter, exit, drop)
1525    pub const FULL: FmtSpan =
1526        FmtSpan(FmtSpan::NEW.0 | FmtSpan::ENTER.0 | FmtSpan::EXIT.0 | FmtSpan::CLOSE.0);
1527
1528    /// Check whether or not a certain flag is set for this [`FmtSpan`]
1529    fn contains(&self, other: FmtSpan) -> bool {
1530        self.clone() & other.clone() == other
1531    }
1532}
1533
1534macro_rules! impl_fmt_span_bit_op {
1535    ($trait:ident, $func:ident, $op:tt) => {
1536        impl std::ops::$trait for FmtSpan {
1537            type Output = FmtSpan;
1538
1539            fn $func(self, rhs: Self) -> Self::Output {
1540                FmtSpan(self.0 $op rhs.0)
1541            }
1542        }
1543    };
1544}
1545
1546macro_rules! impl_fmt_span_bit_assign_op {
1547    ($trait:ident, $func:ident, $op:tt) => {
1548        impl std::ops::$trait for FmtSpan {
1549            fn $func(&mut self, rhs: Self) {
1550                *self = FmtSpan(self.0 $op rhs.0)
1551            }
1552        }
1553    };
1554}
1555
1556impl_fmt_span_bit_op!(BitAnd, bitand, &);
1557impl_fmt_span_bit_op!(BitOr, bitor, |);
1558impl_fmt_span_bit_op!(BitXor, bitxor, ^);
1559
1560impl_fmt_span_bit_assign_op!(BitAndAssign, bitand_assign, &);
1561impl_fmt_span_bit_assign_op!(BitOrAssign, bitor_assign, |);
1562impl_fmt_span_bit_assign_op!(BitXorAssign, bitxor_assign, ^);
1563
1564impl Debug for FmtSpan {
1565    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1566        let mut wrote_flag = false;
1567        let mut write_flags = |flag, flag_str| -> fmt::Result {
1568            if self.contains(flag) {
1569                if wrote_flag {
1570                    f.write_str(" | ")?;
1571                }
1572
1573                f.write_str(flag_str)?;
1574                wrote_flag = true;
1575            }
1576
1577            Ok(())
1578        };
1579
1580        if FmtSpan::NONE | self.clone() == FmtSpan::NONE {
1581            f.write_str("FmtSpan::NONE")?;
1582        } else {
1583            write_flags(FmtSpan::NEW, "FmtSpan::NEW")?;
1584            write_flags(FmtSpan::ENTER, "FmtSpan::ENTER")?;
1585            write_flags(FmtSpan::EXIT, "FmtSpan::EXIT")?;
1586            write_flags(FmtSpan::CLOSE, "FmtSpan::CLOSE")?;
1587        }
1588
1589        Ok(())
1590    }
1591}
1592
1593pub(super) struct FmtSpanConfig {
1594    pub(super) kind: FmtSpan,
1595    pub(super) fmt_timing: bool,
1596}
1597
1598impl FmtSpanConfig {
1599    pub(super) fn without_time(self) -> Self {
1600        Self {
1601            kind: self.kind,
1602            fmt_timing: false,
1603        }
1604    }
1605    pub(super) fn with_kind(self, kind: FmtSpan) -> Self {
1606        Self {
1607            kind,
1608            fmt_timing: self.fmt_timing,
1609        }
1610    }
1611    pub(super) fn trace_new(&self) -> bool {
1612        self.kind.contains(FmtSpan::NEW)
1613    }
1614    pub(super) fn trace_enter(&self) -> bool {
1615        self.kind.contains(FmtSpan::ENTER)
1616    }
1617    pub(super) fn trace_exit(&self) -> bool {
1618        self.kind.contains(FmtSpan::EXIT)
1619    }
1620    pub(super) fn trace_close(&self) -> bool {
1621        self.kind.contains(FmtSpan::CLOSE)
1622    }
1623}
1624
1625impl Debug for FmtSpanConfig {
1626    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1627        self.kind.fmt(f)
1628    }
1629}
1630
1631impl Default for FmtSpanConfig {
1632    fn default() -> Self {
1633        Self {
1634            kind: FmtSpan::NONE,
1635            fmt_timing: true,
1636        }
1637    }
1638}
1639
1640pub(super) struct TimingDisplay(pub(super) u64);
1641impl Display for TimingDisplay {
1642    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1643        let mut t = self.0 as f64;
1644        for unit in ["ns", "µs", "ms", "s"].iter() {
1645            if t < 10.0 {
1646                return write!(f, "{:.2}{}", t, unit);
1647            } else if t < 100.0 {
1648                return write!(f, "{:.1}{}", t, unit);
1649            } else if t < 1000.0 {
1650                return write!(f, "{:.0}{}", t, unit);
1651            }
1652            t /= 1000.0;
1653        }
1654        write!(f, "{:.0}s", t * 1000.0)
1655    }
1656}
1657
1658#[cfg(test)]
1659pub(super) mod test {
1660    use crate::fmt::{test::MockMakeWriter, time::FormatTime};
1661    use tracing::{
1662        self,
1663        collect::with_default,
1664        dispatch::{set_default, Dispatch},
1665    };
1666
1667    use super::{FmtSpan, TimingDisplay, Writer};
1668    use regex::Regex;
1669    use std::fmt;
1670    use std::path::Path;
1671
1672    pub(crate) struct MockTime;
1673    impl FormatTime for MockTime {
1674        fn format_time(&self, w: &mut Writer<'_>) -> fmt::Result {
1675            write!(w, "fake time")
1676        }
1677    }
1678
1679    #[test]
1680    fn disable_everything() {
1681        // This test reproduces https://github.com/tokio-rs/tracing/issues/1354
1682        let make_writer = MockMakeWriter::default();
1683        let subscriber = crate::fmt::Collector::builder()
1684            .with_writer(make_writer.clone())
1685            .without_time()
1686            .with_level(false)
1687            .with_target(false)
1688            .with_thread_ids(false)
1689            .with_thread_names(false);
1690        #[cfg(feature = "ansi")]
1691        let subscriber = subscriber.with_ansi(false);
1692        assert_info_hello(subscriber, make_writer, "hello\n")
1693    }
1694
1695    #[cfg(feature = "ansi")]
1696    #[test]
1697    fn with_ansi_true() {
1698        let expected = "\u{1b}[2mfake time\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mtracing_subscriber::fmt::format::test\u{1b}[0m\u{1b}[2m:\u{1b}[0m hello\n";
1699        assert_info_hello_ansi(true, expected);
1700    }
1701
1702    #[cfg(feature = "ansi")]
1703    #[test]
1704    fn with_ansi_false() {
1705        let expected = "fake time  INFO tracing_subscriber::fmt::format::test: hello\n";
1706        assert_info_hello_ansi(false, expected);
1707    }
1708
1709    #[cfg(feature = "ansi")]
1710    fn assert_info_hello_ansi(is_ansi: bool, expected: &str) {
1711        let make_writer = MockMakeWriter::default();
1712        let subscriber = crate::fmt::Collector::builder()
1713            .with_writer(make_writer.clone())
1714            .with_ansi(is_ansi)
1715            .with_timer(MockTime);
1716        assert_info_hello(subscriber, make_writer, expected)
1717    }
1718
1719    #[cfg(not(feature = "ansi"))]
1720    #[test]
1721    fn without_ansi() {
1722        let make_writer = MockMakeWriter::default();
1723        let expected = "fake time  INFO tracing_subscriber::fmt::format::test: hello\n";
1724        let subscriber = crate::fmt::Collector::builder()
1725            .with_writer(make_writer)
1726            .with_timer(MockTime);
1727        assert_info_hello(subscriber, make_writer, expected);
1728    }
1729
1730    #[test]
1731    fn without_level() {
1732        let make_writer = MockMakeWriter::default();
1733        let subscriber = crate::fmt::Collector::builder()
1734            .with_writer(make_writer.clone())
1735            .with_level(false)
1736            .with_ansi(false)
1737            .with_timer(MockTime);
1738        let expected = "fake time tracing_subscriber::fmt::format::test: hello\n";
1739
1740        assert_info_hello(subscriber, make_writer, expected);
1741    }
1742
1743    #[test]
1744    fn with_line_number_and_file_name() {
1745        let make_writer = MockMakeWriter::default();
1746        let subscriber = crate::fmt::Collector::builder()
1747            .with_writer(make_writer.clone())
1748            .with_file(true)
1749            .with_line_number(true)
1750            .with_level(false)
1751            .with_ansi(false)
1752            .with_timer(MockTime);
1753
1754        let expected = Regex::new(&format!(
1755            "^fake time tracing_subscriber::fmt::format::test: {}:[0-9]+: hello\n$",
1756            current_path()
1757                // if we're on Windows, the path might contain backslashes, which
1758                // have to be escaped before compiling the regex.
1759                .replace('\\', "\\\\")
1760        ))
1761        .unwrap();
1762        let _default = set_default(&subscriber.into());
1763        tracing::info!("hello");
1764        let res = make_writer.get_string();
1765        assert!(expected.is_match(&res));
1766    }
1767
1768    #[test]
1769    fn with_line_number() {
1770        let make_writer = MockMakeWriter::default();
1771        let subscriber = crate::fmt::Collector::builder()
1772            .with_writer(make_writer.clone())
1773            .with_line_number(true)
1774            .with_level(false)
1775            .with_ansi(false)
1776            .with_timer(MockTime);
1777
1778        let expected =
1779            Regex::new("^fake time tracing_subscriber::fmt::format::test: [0-9]+: hello\n$")
1780                .unwrap();
1781        let _default = set_default(&subscriber.into());
1782        tracing::info!("hello");
1783        let res = make_writer.get_string();
1784        assert!(expected.is_match(&res));
1785    }
1786
1787    #[test]
1788    fn with_filename() {
1789        let make_writer = MockMakeWriter::default();
1790        let subscriber = crate::fmt::Collector::builder()
1791            .with_writer(make_writer.clone())
1792            .with_file(true)
1793            .with_level(false)
1794            .with_ansi(false)
1795            .with_timer(MockTime);
1796        let expected = &format!(
1797            "fake time tracing_subscriber::fmt::format::test: {}: hello\n",
1798            current_path(),
1799        );
1800        assert_info_hello(subscriber, make_writer, expected);
1801    }
1802
1803    #[test]
1804    fn with_thread_ids() {
1805        let make_writer = MockMakeWriter::default();
1806        let subscriber = crate::fmt::Collector::builder()
1807            .with_writer(make_writer.clone())
1808            .with_thread_ids(true)
1809            .with_ansi(false)
1810            .with_timer(MockTime);
1811        let expected =
1812            "fake time  INFO ThreadId(NUMERIC) tracing_subscriber::fmt::format::test: hello\n";
1813
1814        assert_info_hello_ignore_numeric(subscriber, make_writer, expected);
1815    }
1816
1817    #[test]
1818    fn pretty_default() {
1819        let make_writer = MockMakeWriter::default();
1820        let subscriber = crate::fmt::Collector::builder()
1821            .pretty()
1822            .with_writer(make_writer.clone())
1823            .with_ansi(false)
1824            .with_timer(MockTime);
1825        let expected = format!(
1826            r#"  fake time  INFO tracing_subscriber::fmt::format::test: hello
1827    at {}:NUMERIC
1828
1829"#,
1830            file!()
1831        );
1832
1833        assert_info_hello_ignore_numeric(subscriber, make_writer, &expected)
1834    }
1835
1836    fn assert_info_hello(subscriber: impl Into<Dispatch>, buf: MockMakeWriter, expected: &str) {
1837        let _default = set_default(&subscriber.into());
1838        tracing::info!("hello");
1839        let result = buf.get_string();
1840
1841        assert_eq!(expected, result)
1842    }
1843
1844    // When numeric characters are used they often form a non-deterministic value as they usually represent things like a thread id or line number.
1845    // This assert method should be used when non-deterministic numeric characters are present.
1846    fn assert_info_hello_ignore_numeric(
1847        subscriber: impl Into<Dispatch>,
1848        buf: MockMakeWriter,
1849        expected: &str,
1850    ) {
1851        let _default = set_default(&subscriber.into());
1852        tracing::info!("hello");
1853
1854        let regex = Regex::new("[0-9]+").unwrap();
1855        let result = buf.get_string();
1856        let result_cleaned = regex.replace_all(&result, "NUMERIC");
1857
1858        assert_eq!(expected, result_cleaned)
1859    }
1860
1861    #[test]
1862    fn overridden_parents() {
1863        let make_writer = MockMakeWriter::default();
1864        let collector = crate::fmt::Collector::builder()
1865            .with_writer(make_writer.clone())
1866            .with_level(false)
1867            .with_ansi(false)
1868            .with_timer(MockTime)
1869            .finish();
1870
1871        with_default(collector, || {
1872            let span1 = tracing::info_span!("span1");
1873            let span2 = tracing::info_span!(parent: &span1, "span2");
1874            tracing::info!(parent: &span2, "hello");
1875        });
1876        assert_eq!(
1877            "fake time span1:span2: tracing_subscriber::fmt::format::test: hello\n",
1878            make_writer.get_string()
1879        );
1880    }
1881
1882    #[test]
1883    fn overridden_parents_in_scope() {
1884        let make_writer = MockMakeWriter::default();
1885        let subscriber = crate::fmt::Collector::builder()
1886            .with_writer(make_writer.clone())
1887            .with_level(false)
1888            .with_ansi(false)
1889            .with_timer(MockTime)
1890            .finish();
1891
1892        with_default(subscriber, || {
1893            let span1 = tracing::info_span!("span1");
1894            let span2 = tracing::info_span!(parent: &span1, "span2");
1895            let span3 = tracing::info_span!("span3");
1896            let _e3 = span3.enter();
1897
1898            tracing::info!("hello");
1899            assert_eq!(
1900                "fake time span3: tracing_subscriber::fmt::format::test: hello\n",
1901                make_writer.get_string().as_str()
1902            );
1903
1904            tracing::info!(parent: &span2, "hello");
1905            assert_eq!(
1906                "fake time span1:span2: tracing_subscriber::fmt::format::test: hello\n",
1907                make_writer.get_string().as_str()
1908            );
1909        });
1910    }
1911
1912    #[test]
1913    fn format_nanos() {
1914        fn fmt(t: u64) -> String {
1915            TimingDisplay(t).to_string()
1916        }
1917
1918        assert_eq!(fmt(1), "1.00ns");
1919        assert_eq!(fmt(12), "12.0ns");
1920        assert_eq!(fmt(123), "123ns");
1921        assert_eq!(fmt(1234), "1.23µs");
1922        assert_eq!(fmt(12345), "12.3µs");
1923        assert_eq!(fmt(123456), "123µs");
1924        assert_eq!(fmt(1234567), "1.23ms");
1925        assert_eq!(fmt(12345678), "12.3ms");
1926        assert_eq!(fmt(123456789), "123ms");
1927        assert_eq!(fmt(1234567890), "1.23s");
1928        assert_eq!(fmt(12345678901), "12.3s");
1929        assert_eq!(fmt(123456789012), "123s");
1930        assert_eq!(fmt(1234567890123), "1235s");
1931    }
1932
1933    #[test]
1934    fn fmt_span_combinations() {
1935        let f = FmtSpan::NONE;
1936        assert!(!f.contains(FmtSpan::NEW));
1937        assert!(!f.contains(FmtSpan::ENTER));
1938        assert!(!f.contains(FmtSpan::EXIT));
1939        assert!(!f.contains(FmtSpan::CLOSE));
1940
1941        let f = FmtSpan::ACTIVE;
1942        assert!(!f.contains(FmtSpan::NEW));
1943        assert!(f.contains(FmtSpan::ENTER));
1944        assert!(f.contains(FmtSpan::EXIT));
1945        assert!(!f.contains(FmtSpan::CLOSE));
1946
1947        let f = FmtSpan::FULL;
1948        assert!(f.contains(FmtSpan::NEW));
1949        assert!(f.contains(FmtSpan::ENTER));
1950        assert!(f.contains(FmtSpan::EXIT));
1951        assert!(f.contains(FmtSpan::CLOSE));
1952
1953        let f = FmtSpan::NEW | FmtSpan::CLOSE;
1954        assert!(f.contains(FmtSpan::NEW));
1955        assert!(!f.contains(FmtSpan::ENTER));
1956        assert!(!f.contains(FmtSpan::EXIT));
1957        assert!(f.contains(FmtSpan::CLOSE));
1958    }
1959
1960    /// Returns the test's module path.
1961    fn current_path() -> String {
1962        Path::new("tracing-subscriber")
1963            .join("src")
1964            .join("fmt")
1965            .join("format")
1966            .join("mod.rs")
1967            .to_str()
1968            .expect("path must not contain invalid unicode")
1969            .to_owned()
1970    }
1971}