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