better_tracing/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 better_tracing::fmt::{
118/// format::{self, FormatEvent, FormatFields},
119/// FmtContext,
120/// FormattedFields,
121/// };
122/// use better_tracing::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 = better_tracing::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 = better_tracing::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/// better_tracing::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 better_tracing::fmt::format;
640 /// better_tracing::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>
1337where
1338 S: Subscriber + for<'lookup> LookupSpan<'lookup>,
1339{
1340 ctx: &'a FmtContext<'a, S, N>,
1341 span: Option<&'a span::Id>,
1342 #[cfg(feature = "ansi")]
1343 ansi: bool,
1344}
1345
1346impl<'a, S, N: 'a> FmtCtx<'a, S, N>
1347where
1348 S: Subscriber + for<'lookup> LookupSpan<'lookup>,
1349 N: for<'writer> FormatFields<'writer> + 'static,
1350{
1351 #[cfg(feature = "ansi")]
1352 pub(crate) fn new(
1353 ctx: &'a FmtContext<'_, S, N>,
1354 span: Option<&'a span::Id>,
1355 ansi: bool,
1356 ) -> Self {
1357 Self { ctx, span, ansi }
1358 }
1359
1360 #[cfg(not(feature = "ansi"))]
1361 pub(crate) fn new(ctx: &'a FmtContext<'_, S, N>, span: Option<&'a span::Id>) -> Self {
1362 Self { ctx, span }
1363 }
1364
1365 fn bold(&self) -> Style {
1366 #[cfg(feature = "ansi")]
1367 {
1368 if self.ansi {
1369 return Style::new().bold();
1370 }
1371 }
1372
1373 Style::new()
1374 }
1375}
1376
1377impl<'a, S, N: 'a> fmt::Display for FmtCtx<'a, S, N>
1378where
1379 S: Subscriber + for<'lookup> LookupSpan<'lookup>,
1380 N: for<'writer> FormatFields<'writer> + 'static,
1381{
1382 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1383 let bold = self.bold();
1384 let mut seen = false;
1385
1386 let span = self
1387 .span
1388 .and_then(|id| self.ctx.ctx.span(id))
1389 .or_else(|| self.ctx.ctx.lookup_current());
1390
1391 let scope = span.into_iter().flat_map(|span| span.scope().from_root());
1392
1393 for span in scope {
1394 seen = true;
1395 write!(f, "{}:", bold.paint(span.metadata().name()))?;
1396 }
1397
1398 if seen {
1399 f.write_char(' ')?;
1400 }
1401 Ok(())
1402 }
1403}
1404
1405#[cfg(not(feature = "ansi"))]
1406struct Style;
1407
1408#[cfg(not(feature = "ansi"))]
1409impl Style {
1410 fn new() -> Self {
1411 Style
1412 }
1413
1414 fn bold(self) -> Self {
1415 self
1416 }
1417
1418 fn paint(&self, d: impl fmt::Display) -> impl fmt::Display {
1419 d
1420 }
1421
1422 fn prefix(&self) -> impl fmt::Display {
1423 ""
1424 }
1425
1426 fn suffix(&self) -> impl fmt::Display {
1427 ""
1428 }
1429}
1430
1431struct FmtThreadName<'a> {
1432 name: &'a str,
1433}
1434
1435impl<'a> FmtThreadName<'a> {
1436 pub(crate) fn new(name: &'a str) -> Self {
1437 Self { name }
1438 }
1439}
1440
1441impl fmt::Display for FmtThreadName<'_> {
1442 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1443 use std::sync::atomic::{
1444 AtomicUsize,
1445 Ordering::{AcqRel, Acquire, Relaxed},
1446 };
1447
1448 // Track the longest thread name length we've seen so far in an atomic,
1449 // so that it can be updated by any thread.
1450 static MAX_LEN: AtomicUsize = AtomicUsize::new(0);
1451 let len = self.name.len();
1452 // Snapshot the current max thread name length.
1453 let mut max_len = MAX_LEN.load(Relaxed);
1454
1455 while len > max_len {
1456 // Try to set a new max length, if it is still the value we took a
1457 // snapshot of.
1458 match MAX_LEN.compare_exchange(max_len, len, AcqRel, Acquire) {
1459 // We successfully set the new max value
1460 Ok(_) => break,
1461 // Another thread set a new max value since we last observed
1462 // it! It's possible that the new length is actually longer than
1463 // ours, so we'll loop again and check whether our length is
1464 // still the longest. If not, we'll just use the newer value.
1465 Err(actual) => max_len = actual,
1466 }
1467 }
1468
1469 // pad thread name using `max_len`
1470 write!(f, "{:>width$}", self.name, width = max_len)
1471 }
1472}
1473
1474struct FmtLevel<'a> {
1475 level: &'a Level,
1476 #[cfg(feature = "ansi")]
1477 ansi: bool,
1478}
1479
1480impl<'a> FmtLevel<'a> {
1481 #[cfg(feature = "ansi")]
1482 pub(crate) fn new(level: &'a Level, ansi: bool) -> Self {
1483 Self { level, ansi }
1484 }
1485
1486 #[cfg(not(feature = "ansi"))]
1487 pub(crate) fn new(level: &'a Level) -> Self {
1488 Self { level }
1489 }
1490}
1491
1492const TRACE_STR: &str = "TRACE";
1493const DEBUG_STR: &str = "DEBUG";
1494const INFO_STR: &str = " INFO";
1495const WARN_STR: &str = " WARN";
1496const ERROR_STR: &str = "ERROR";
1497
1498#[cfg(not(feature = "ansi"))]
1499impl<'a> fmt::Display for FmtLevel<'a> {
1500 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1501 match *self.level {
1502 Level::TRACE => f.pad(TRACE_STR),
1503 Level::DEBUG => f.pad(DEBUG_STR),
1504 Level::INFO => f.pad(INFO_STR),
1505 Level::WARN => f.pad(WARN_STR),
1506 Level::ERROR => f.pad(ERROR_STR),
1507 }
1508 }
1509}
1510
1511#[cfg(feature = "ansi")]
1512impl fmt::Display for FmtLevel<'_> {
1513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1514 if self.ansi {
1515 match *self.level {
1516 Level::TRACE => write!(f, "{}", Color::Purple.paint(TRACE_STR)),
1517 Level::DEBUG => write!(f, "{}", Color::Blue.paint(DEBUG_STR)),
1518 Level::INFO => write!(f, "{}", Color::Green.paint(INFO_STR)),
1519 Level::WARN => write!(f, "{}", Color::Yellow.paint(WARN_STR)),
1520 Level::ERROR => write!(f, "{}", Color::Red.paint(ERROR_STR)),
1521 }
1522 } else {
1523 match *self.level {
1524 Level::TRACE => f.pad(TRACE_STR),
1525 Level::DEBUG => f.pad(DEBUG_STR),
1526 Level::INFO => f.pad(INFO_STR),
1527 Level::WARN => f.pad(WARN_STR),
1528 Level::ERROR => f.pad(ERROR_STR),
1529 }
1530 }
1531 }
1532}
1533
1534// === impl FieldFn ===
1535
1536impl<'a, F> MakeVisitor<Writer<'a>> for FieldFn<F>
1537where
1538 F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result + Clone,
1539{
1540 type Visitor = FieldFnVisitor<'a, F>;
1541
1542 fn make_visitor(&self, writer: Writer<'a>) -> Self::Visitor {
1543 FieldFnVisitor {
1544 writer,
1545 f: self.0.clone(),
1546 result: Ok(()),
1547 }
1548 }
1549}
1550
1551impl<'a, F> Visit for FieldFnVisitor<'a, F>
1552where
1553 F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result,
1554{
1555 fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
1556 if self.result.is_ok() {
1557 self.result = (self.f)(&mut self.writer, field, value)
1558 }
1559 }
1560}
1561
1562impl<'a, F> VisitOutput<fmt::Result> for FieldFnVisitor<'a, F>
1563where
1564 F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result,
1565{
1566 fn finish(self) -> fmt::Result {
1567 self.result
1568 }
1569}
1570
1571impl<'a, F> VisitFmt for FieldFnVisitor<'a, F>
1572where
1573 F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result,
1574{
1575 fn writer(&mut self) -> &mut dyn fmt::Write {
1576 &mut self.writer
1577 }
1578}
1579
1580impl<F> fmt::Debug for FieldFnVisitor<'_, F> {
1581 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1582 f.debug_struct("FieldFnVisitor")
1583 .field("f", &format_args!("{}", std::any::type_name::<F>()))
1584 .field("writer", &self.writer)
1585 .field("result", &self.result)
1586 .finish()
1587 }
1588}
1589
1590// === printing synthetic Span events ===
1591
1592/// Configures what points in the span lifecycle are logged as events.
1593///
1594/// See also [`with_span_events`](super::SubscriberBuilder.html::with_span_events).
1595#[derive(Clone, Eq, PartialEq, Ord, PartialOrd)]
1596pub struct FmtSpan(u8);
1597
1598impl FmtSpan {
1599 /// one event when span is created
1600 pub const NEW: FmtSpan = FmtSpan(1 << 0);
1601 /// one event per enter of a span
1602 pub const ENTER: FmtSpan = FmtSpan(1 << 1);
1603 /// one event per exit of a span
1604 pub const EXIT: FmtSpan = FmtSpan(1 << 2);
1605 /// one event when the span is dropped
1606 pub const CLOSE: FmtSpan = FmtSpan(1 << 3);
1607
1608 /// spans are ignored (this is the default)
1609 pub const NONE: FmtSpan = FmtSpan(0);
1610 /// one event per enter/exit of a span
1611 pub const ACTIVE: FmtSpan = FmtSpan(FmtSpan::ENTER.0 | FmtSpan::EXIT.0);
1612 /// events at all points (new, enter, exit, drop)
1613 pub const FULL: FmtSpan =
1614 FmtSpan(FmtSpan::NEW.0 | FmtSpan::ENTER.0 | FmtSpan::EXIT.0 | FmtSpan::CLOSE.0);
1615
1616 /// Check whether or not a certain flag is set for this [`FmtSpan`]
1617 fn contains(&self, other: FmtSpan) -> bool {
1618 self.clone() & other.clone() == other
1619 }
1620}
1621
1622macro_rules! impl_fmt_span_bit_op {
1623 ($trait:ident, $func:ident, $op:tt) => {
1624 impl std::ops::$trait for FmtSpan {
1625 type Output = FmtSpan;
1626
1627 fn $func(self, rhs: Self) -> Self::Output {
1628 FmtSpan(self.0 $op rhs.0)
1629 }
1630 }
1631 };
1632}
1633
1634macro_rules! impl_fmt_span_bit_assign_op {
1635 ($trait:ident, $func:ident, $op:tt) => {
1636 impl std::ops::$trait for FmtSpan {
1637 fn $func(&mut self, rhs: Self) {
1638 *self = FmtSpan(self.0 $op rhs.0)
1639 }
1640 }
1641 };
1642}
1643
1644impl_fmt_span_bit_op!(BitAnd, bitand, &);
1645impl_fmt_span_bit_op!(BitOr, bitor, |);
1646impl_fmt_span_bit_op!(BitXor, bitxor, ^);
1647
1648impl_fmt_span_bit_assign_op!(BitAndAssign, bitand_assign, &);
1649impl_fmt_span_bit_assign_op!(BitOrAssign, bitor_assign, |);
1650impl_fmt_span_bit_assign_op!(BitXorAssign, bitxor_assign, ^);
1651
1652impl Debug for FmtSpan {
1653 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1654 let mut wrote_flag = false;
1655 let mut write_flags = |flag, flag_str| -> fmt::Result {
1656 if self.contains(flag) {
1657 if wrote_flag {
1658 f.write_str(" | ")?;
1659 }
1660
1661 f.write_str(flag_str)?;
1662 wrote_flag = true;
1663 }
1664
1665 Ok(())
1666 };
1667
1668 if FmtSpan::NONE | self.clone() == FmtSpan::NONE {
1669 f.write_str("FmtSpan::NONE")?;
1670 } else {
1671 write_flags(FmtSpan::NEW, "FmtSpan::NEW")?;
1672 write_flags(FmtSpan::ENTER, "FmtSpan::ENTER")?;
1673 write_flags(FmtSpan::EXIT, "FmtSpan::EXIT")?;
1674 write_flags(FmtSpan::CLOSE, "FmtSpan::CLOSE")?;
1675 }
1676
1677 Ok(())
1678 }
1679}
1680
1681pub(super) struct FmtSpanConfig {
1682 pub(super) kind: FmtSpan,
1683 pub(super) fmt_timing: bool,
1684}
1685
1686impl FmtSpanConfig {
1687 pub(super) fn without_time(self) -> Self {
1688 Self {
1689 kind: self.kind,
1690 fmt_timing: false,
1691 }
1692 }
1693 pub(super) fn with_kind(self, kind: FmtSpan) -> Self {
1694 Self {
1695 kind,
1696 fmt_timing: self.fmt_timing,
1697 }
1698 }
1699 pub(super) fn trace_new(&self) -> bool {
1700 self.kind.contains(FmtSpan::NEW)
1701 }
1702 pub(super) fn trace_enter(&self) -> bool {
1703 self.kind.contains(FmtSpan::ENTER)
1704 }
1705 pub(super) fn trace_exit(&self) -> bool {
1706 self.kind.contains(FmtSpan::EXIT)
1707 }
1708 pub(super) fn trace_close(&self) -> bool {
1709 self.kind.contains(FmtSpan::CLOSE)
1710 }
1711}
1712
1713impl Debug for FmtSpanConfig {
1714 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1715 self.kind.fmt(f)
1716 }
1717}
1718
1719impl Default for FmtSpanConfig {
1720 fn default() -> Self {
1721 Self {
1722 kind: FmtSpan::NONE,
1723 fmt_timing: true,
1724 }
1725 }
1726}
1727
1728pub(super) struct TimingDisplay(pub(super) u64);
1729impl Display for TimingDisplay {
1730 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1731 let mut t = self.0 as f64;
1732 for unit in ["ns", "µs", "ms", "s"].iter() {
1733 if t < 10.0 {
1734 return write!(f, "{:.2}{}", t, unit);
1735 } else if t < 100.0 {
1736 return write!(f, "{:.1}{}", t, unit);
1737 } else if t < 1000.0 {
1738 return write!(f, "{:.0}{}", t, unit);
1739 }
1740 t /= 1000.0;
1741 }
1742 write!(f, "{:.0}s", t * 1000.0)
1743 }
1744}
1745
1746#[cfg(test)]
1747pub(super) mod test {
1748 use crate::fmt::{test::MockMakeWriter, time::FormatTime};
1749 use tracing::{
1750 self,
1751 dispatcher::{set_default, Dispatch},
1752 subscriber::with_default,
1753 };
1754
1755 use super::*;
1756
1757 use regex::Regex;
1758 use std::{fmt, path::Path};
1759
1760 pub(crate) struct MockTime;
1761 impl FormatTime for MockTime {
1762 fn format_time(&self, w: &mut Writer<'_>) -> fmt::Result {
1763 write!(w, "fake time")
1764 }
1765 }
1766
1767 #[test]
1768 fn disable_everything() {
1769 // This test reproduces https://github.com/tokio-rs/tracing/issues/1354
1770 let make_writer = MockMakeWriter::default();
1771 let subscriber = crate::fmt::Subscriber::builder()
1772 .with_writer(make_writer.clone())
1773 .without_time()
1774 .with_level(false)
1775 .with_target(false)
1776 .with_thread_ids(false)
1777 .with_thread_names(false);
1778 #[cfg(feature = "ansi")]
1779 let subscriber = subscriber.with_ansi(false);
1780 assert_info_hello(subscriber, make_writer, "hello\n")
1781 }
1782
1783 fn test_ansi<T>(
1784 is_ansi: bool,
1785 expected: &str,
1786 builder: crate::fmt::SubscriberBuilder<DefaultFields, Format<T>>,
1787 ) where
1788 Format<T, MockTime>: FormatEvent<crate::Registry, DefaultFields>,
1789 T: Send + Sync + 'static,
1790 {
1791 let make_writer = MockMakeWriter::default();
1792 let subscriber = builder
1793 .with_writer(make_writer.clone())
1794 .with_ansi(is_ansi)
1795 .with_timer(MockTime);
1796 run_test(subscriber, make_writer, expected)
1797 }
1798
1799 #[cfg(not(feature = "ansi"))]
1800 fn test_without_ansi<T>(
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,
1806 {
1807 let make_writer = MockMakeWriter::default();
1808 let subscriber = builder.with_writer(make_writer).with_timer(MockTime);
1809 run_test(subscriber, make_writer, expected)
1810 }
1811
1812 fn test_without_level<T>(
1813 expected: &str,
1814 builder: crate::fmt::SubscriberBuilder<DefaultFields, Format<T>>,
1815 ) where
1816 Format<T, MockTime>: FormatEvent<crate::Registry, DefaultFields>,
1817 T: Send + Sync + 'static,
1818 {
1819 let make_writer = MockMakeWriter::default();
1820 let subscriber = builder
1821 .with_writer(make_writer.clone())
1822 .with_level(false)
1823 .with_ansi(false)
1824 .with_timer(MockTime);
1825 run_test(subscriber, make_writer, expected);
1826 }
1827
1828 #[test]
1829 fn with_line_number_and_file_name() {
1830 let make_writer = MockMakeWriter::default();
1831 let subscriber = crate::fmt::Subscriber::builder()
1832 .with_writer(make_writer.clone())
1833 .with_file(true)
1834 .with_line_number(true)
1835 .with_level(false)
1836 .with_ansi(false)
1837 .with_timer(MockTime);
1838
1839 let expected = Regex::new(&format!(
1840 "^fake time better_tracing::fmt::format::test: {}:[0-9]+: hello\n$",
1841 current_path()
1842 // if we're on Windows, the path might contain backslashes, which
1843 // have to be escaped before compiling the regex.
1844 .replace('\\', "\\\\")
1845 ))
1846 .unwrap();
1847 let _default = set_default(&subscriber.into());
1848 tracing::info!("hello");
1849 let res = make_writer.get_string();
1850 assert!(expected.is_match(&res));
1851 }
1852
1853 #[test]
1854 fn with_line_number() {
1855 let make_writer = MockMakeWriter::default();
1856 let subscriber = crate::fmt::Subscriber::builder()
1857 .with_writer(make_writer.clone())
1858 .with_line_number(true)
1859 .with_level(false)
1860 .with_ansi(false)
1861 .with_timer(MockTime);
1862
1863 let expected =
1864 Regex::new("^fake time better_tracing::fmt::format::test: [0-9]+: hello\n$").unwrap();
1865 let _default = set_default(&subscriber.into());
1866 tracing::info!("hello");
1867 let res = make_writer.get_string();
1868 assert!(expected.is_match(&res));
1869 }
1870
1871 #[test]
1872 fn with_filename() {
1873 let make_writer = MockMakeWriter::default();
1874 let subscriber = crate::fmt::Subscriber::builder()
1875 .with_writer(make_writer.clone())
1876 .with_file(true)
1877 .with_level(false)
1878 .with_ansi(false)
1879 .with_timer(MockTime);
1880 let expected = &format!(
1881 "fake time better_tracing::fmt::format::test: {}: hello\n",
1882 current_path(),
1883 );
1884 assert_info_hello(subscriber, make_writer, expected);
1885 }
1886
1887 #[test]
1888 fn with_thread_ids() {
1889 let make_writer = MockMakeWriter::default();
1890 let subscriber = crate::fmt::Subscriber::builder()
1891 .with_writer(make_writer.clone())
1892 .with_thread_ids(true)
1893 .with_ansi(false)
1894 .with_timer(MockTime);
1895 let expected =
1896 "fake time INFO ThreadId(NUMERIC) better_tracing::fmt::format::test: hello\n";
1897
1898 assert_info_hello_ignore_numeric(subscriber, make_writer, expected);
1899 }
1900
1901 #[test]
1902 fn pretty_default() {
1903 let make_writer = MockMakeWriter::default();
1904 let subscriber = crate::fmt::Subscriber::builder()
1905 .pretty()
1906 .with_writer(make_writer.clone())
1907 .with_ansi(false)
1908 .with_timer(MockTime);
1909 let expected = format!(
1910 r#" fake time INFO better_tracing::fmt::format::test: hello
1911 at {}:NUMERIC
1912
1913"#,
1914 file!()
1915 );
1916
1917 assert_info_hello_ignore_numeric(subscriber, make_writer, &expected)
1918 }
1919
1920 fn assert_info_hello(subscriber: impl Into<Dispatch>, buf: MockMakeWriter, expected: &str) {
1921 let _default = set_default(&subscriber.into());
1922 tracing::info!("hello");
1923 let result = buf.get_string();
1924
1925 assert_eq!(expected, result)
1926 }
1927
1928 // When numeric characters are used they often form a non-deterministic value as they usually represent things like a thread id or line number.
1929 // This assert method should be used when non-deterministic numeric characters are present.
1930 fn assert_info_hello_ignore_numeric(
1931 subscriber: impl Into<Dispatch>,
1932 buf: MockMakeWriter,
1933 expected: &str,
1934 ) {
1935 let _default = set_default(&subscriber.into());
1936 tracing::info!("hello");
1937
1938 let regex = Regex::new("[0-9]+").unwrap();
1939 let result = buf.get_string();
1940 let result_cleaned = regex.replace_all(&result, "NUMERIC");
1941
1942 assert_eq!(expected, result_cleaned)
1943 }
1944
1945 fn test_overridden_parents<T>(
1946 expected: &str,
1947 builder: crate::fmt::SubscriberBuilder<DefaultFields, Format<T>>,
1948 ) where
1949 Format<T, MockTime>: FormatEvent<crate::Registry, DefaultFields>,
1950 T: Send + Sync + 'static,
1951 {
1952 let make_writer = MockMakeWriter::default();
1953 let subscriber = builder
1954 .with_writer(make_writer.clone())
1955 .with_level(false)
1956 .with_ansi(false)
1957 .with_timer(MockTime)
1958 .finish();
1959
1960 with_default(subscriber, || {
1961 let span1 = tracing::info_span!("span1", span = 1);
1962 let span2 = tracing::info_span!(parent: &span1, "span2", span = 2);
1963 tracing::info!(parent: &span2, "hello");
1964 });
1965 assert_eq!(expected, make_writer.get_string());
1966 }
1967
1968 fn test_overridden_parents_in_scope<T>(
1969 expected1: &str,
1970 expected2: &str,
1971 builder: crate::fmt::SubscriberBuilder<DefaultFields, Format<T>>,
1972 ) where
1973 Format<T, MockTime>: FormatEvent<crate::Registry, DefaultFields>,
1974 T: Send + Sync + 'static,
1975 {
1976 let make_writer = MockMakeWriter::default();
1977 let subscriber = builder
1978 .with_writer(make_writer.clone())
1979 .with_level(false)
1980 .with_ansi(false)
1981 .with_timer(MockTime)
1982 .finish();
1983
1984 with_default(subscriber, || {
1985 let span1 = tracing::info_span!("span1", span = 1);
1986 let span2 = tracing::info_span!(parent: &span1, "span2", span = 2);
1987 let span3 = tracing::info_span!("span3", span = 3);
1988 let _e3 = span3.enter();
1989
1990 tracing::info!("hello");
1991 assert_eq!(expected1, make_writer.get_string().as_str());
1992
1993 tracing::info!(parent: &span2, "hello");
1994 assert_eq!(expected2, make_writer.get_string().as_str());
1995 });
1996 }
1997
1998 fn run_test(subscriber: impl Into<Dispatch>, buf: MockMakeWriter, expected: &str) {
1999 let _default = set_default(&subscriber.into());
2000 tracing::info!("hello");
2001 assert_eq!(expected, buf.get_string())
2002 }
2003
2004 mod default {
2005 use super::*;
2006
2007 #[test]
2008 fn with_thread_ids() {
2009 let make_writer = MockMakeWriter::default();
2010 let subscriber = crate::fmt::Subscriber::builder()
2011 .with_writer(make_writer.clone())
2012 .with_thread_ids(true)
2013 .with_ansi(false)
2014 .with_timer(MockTime);
2015 let expected =
2016 "fake time INFO ThreadId(NUMERIC) better_tracing::fmt::format::test: hello\n";
2017
2018 assert_info_hello_ignore_numeric(subscriber, make_writer, expected);
2019 }
2020
2021 #[cfg(feature = "ansi")]
2022 #[test]
2023 fn with_ansi_true() {
2024 let expected = "\u{1b}[2mfake time\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mbetter_tracing::fmt::format::test\u{1b}[0m\u{1b}[2m:\u{1b}[0m hello\n";
2025 test_ansi(true, expected, crate::fmt::Subscriber::builder());
2026 }
2027
2028 #[cfg(feature = "ansi")]
2029 #[test]
2030 fn with_ansi_false() {
2031 let expected = "fake time INFO better_tracing::fmt::format::test: hello\n";
2032 test_ansi(false, expected, crate::fmt::Subscriber::builder());
2033 }
2034
2035 #[cfg(not(feature = "ansi"))]
2036 #[test]
2037 fn without_ansi() {
2038 let expected = "fake time INFO better_tracing::fmt::format::test: hello\n";
2039 test_without_ansi(expected, crate::fmt::Subscriber::builder())
2040 }
2041
2042 #[test]
2043 fn without_level() {
2044 let expected = "fake time better_tracing::fmt::format::test: hello\n";
2045 test_without_level(expected, crate::fmt::Subscriber::builder())
2046 }
2047
2048 #[test]
2049 fn overridden_parents() {
2050 let expected =
2051 "fake time span1{span=1}:span2{span=2}: better_tracing::fmt::format::test: hello\n";
2052 test_overridden_parents(expected, crate::fmt::Subscriber::builder())
2053 }
2054
2055 #[test]
2056 fn overridden_parents_in_scope() {
2057 test_overridden_parents_in_scope(
2058 "fake time span3{span=3}: better_tracing::fmt::format::test: hello\n",
2059 "fake time span1{span=1}:span2{span=2}: better_tracing::fmt::format::test: hello\n",
2060 crate::fmt::Subscriber::builder(),
2061 )
2062 }
2063 }
2064
2065 mod compact {
2066 use super::*;
2067
2068 #[cfg(feature = "ansi")]
2069 #[test]
2070 fn with_ansi_true() {
2071 let expected = "\u{1b}[2mfake time\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mbetter_tracing::fmt::format::test\u{1b}[0m\u{1b}[2m:\u{1b}[0m hello\n";
2072 test_ansi(true, expected, crate::fmt::Subscriber::builder().compact())
2073 }
2074
2075 #[cfg(feature = "ansi")]
2076 #[test]
2077 fn with_ansi_false() {
2078 let expected = "fake time INFO better_tracing::fmt::format::test: hello\n";
2079 test_ansi(false, expected, crate::fmt::Subscriber::builder().compact());
2080 }
2081
2082 #[cfg(not(feature = "ansi"))]
2083 #[test]
2084 fn without_ansi() {
2085 let expected = "fake time INFO better_tracing::fmt::format::test: hello\n";
2086 test_without_ansi(expected, crate::fmt::Subscriber::builder().compact())
2087 }
2088
2089 #[test]
2090 fn without_level() {
2091 let expected = "fake time better_tracing::fmt::format::test: hello\n";
2092 test_without_level(expected, crate::fmt::Subscriber::builder().compact());
2093 }
2094
2095 #[test]
2096 fn overridden_parents() {
2097 let expected =
2098 "fake time span1:span2: better_tracing::fmt::format::test: hello span=1 span=2\n";
2099 test_overridden_parents(expected, crate::fmt::Subscriber::builder().compact())
2100 }
2101
2102 #[test]
2103 fn overridden_parents_in_scope() {
2104 test_overridden_parents_in_scope(
2105 "fake time span3: better_tracing::fmt::format::test: hello span=3\n",
2106 "fake time span1:span2: better_tracing::fmt::format::test: hello span=1 span=2\n",
2107 crate::fmt::Subscriber::builder().compact(),
2108 )
2109 }
2110 }
2111
2112 mod pretty {
2113 use super::*;
2114
2115 #[test]
2116 fn pretty_default() {
2117 let make_writer = MockMakeWriter::default();
2118 let subscriber = crate::fmt::Subscriber::builder()
2119 .pretty()
2120 .with_writer(make_writer.clone())
2121 .with_ansi(false)
2122 .with_timer(MockTime);
2123 let expected = format!(
2124 " fake time INFO better_tracing::fmt::format::test: hello\n at {}:NUMERIC\n\n",
2125 file!()
2126 );
2127
2128 assert_info_hello_ignore_numeric(subscriber, make_writer, &expected)
2129 }
2130 }
2131
2132 #[test]
2133 fn format_nanos() {
2134 fn fmt(t: u64) -> String {
2135 TimingDisplay(t).to_string()
2136 }
2137
2138 assert_eq!(fmt(1), "1.00ns");
2139 assert_eq!(fmt(12), "12.0ns");
2140 assert_eq!(fmt(123), "123ns");
2141 assert_eq!(fmt(1234), "1.23µs");
2142 assert_eq!(fmt(12345), "12.3µs");
2143 assert_eq!(fmt(123456), "123µs");
2144 assert_eq!(fmt(1234567), "1.23ms");
2145 assert_eq!(fmt(12345678), "12.3ms");
2146 assert_eq!(fmt(123456789), "123ms");
2147 assert_eq!(fmt(1234567890), "1.23s");
2148 assert_eq!(fmt(12345678901), "12.3s");
2149 assert_eq!(fmt(123456789012), "123s");
2150 assert_eq!(fmt(1234567890123), "1235s");
2151 }
2152
2153 #[test]
2154 fn fmt_span_combinations() {
2155 let f = FmtSpan::NONE;
2156 assert!(!f.contains(FmtSpan::NEW));
2157 assert!(!f.contains(FmtSpan::ENTER));
2158 assert!(!f.contains(FmtSpan::EXIT));
2159 assert!(!f.contains(FmtSpan::CLOSE));
2160
2161 let f = FmtSpan::ACTIVE;
2162 assert!(!f.contains(FmtSpan::NEW));
2163 assert!(f.contains(FmtSpan::ENTER));
2164 assert!(f.contains(FmtSpan::EXIT));
2165 assert!(!f.contains(FmtSpan::CLOSE));
2166
2167 let f = FmtSpan::FULL;
2168 assert!(f.contains(FmtSpan::NEW));
2169 assert!(f.contains(FmtSpan::ENTER));
2170 assert!(f.contains(FmtSpan::EXIT));
2171 assert!(f.contains(FmtSpan::CLOSE));
2172
2173 let f = FmtSpan::NEW | FmtSpan::CLOSE;
2174 assert!(f.contains(FmtSpan::NEW));
2175 assert!(!f.contains(FmtSpan::ENTER));
2176 assert!(!f.contains(FmtSpan::EXIT));
2177 assert!(f.contains(FmtSpan::CLOSE));
2178 }
2179
2180 /// Returns the test's module path.
2181 fn current_path() -> String {
2182 Path::new("src")
2183 .join("fmt")
2184 .join("format")
2185 .join("mod.rs")
2186 .to_str()
2187 .expect("path must not contain invalid unicode")
2188 .to_owned()
2189 }
2190}