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