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