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 nu_ansi_term::{Color, 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 [`nu_ansi_term`] and [`owo-colors`] can be used to add ANSI |
105 | /// escape codes to formatted output. |
106 | /// |
107 | /// * The actual [`Event`] to be formatted. |
108 | /// |
109 | /// # Examples |
110 | /// |
111 | /// This example re-implements a simiplified version of this crate's [default |
112 | /// formatter]: |
113 | /// |
114 | /// ```rust |
115 | /// use std::fmt; |
116 | /// use tracing_core::{Subscriber, Event}; |
117 | /// use tracing_subscriber::fmt::{ |
118 | /// format::{self, FormatEvent, FormatFields}, |
119 | /// FmtContext, |
120 | /// FormattedFields, |
121 | /// }; |
122 | /// use tracing_subscriber::registry::LookupSpan; |
123 | /// |
124 | /// struct MyFormatter; |
125 | /// |
126 | /// impl<S, N> FormatEvent<S, N> for MyFormatter |
127 | /// where |
128 | /// S: Subscriber + for<'a> LookupSpan<'a>, |
129 | /// N: for<'a> FormatFields<'a> + 'static, |
130 | /// { |
131 | /// fn format_event( |
132 | /// &self, |
133 | /// ctx: &FmtContext<'_, S, N>, |
134 | /// mut writer: format::Writer<'_>, |
135 | /// event: &Event<'_>, |
136 | /// ) -> fmt::Result { |
137 | /// // Format values from the event's's metadata: |
138 | /// let metadata = event.metadata(); |
139 | /// write!(&mut writer, "{} {}: " , metadata.level(), metadata.target())?; |
140 | /// |
141 | /// // Format all the spans in the event's span context. |
142 | /// if let Some(scope) = ctx.event_scope() { |
143 | /// for span in scope.from_root() { |
144 | /// write!(writer, "{}" , span.name())?; |
145 | /// |
146 | /// // `FormattedFields` is a formatted representation of the span's |
147 | /// // fields, which is stored in its extensions by the `fmt` layer's |
148 | /// // `new_span` method. The fields will have been formatted |
149 | /// // by the same field formatter that's provided to the event |
150 | /// // formatter in the `FmtContext`. |
151 | /// let ext = span.extensions(); |
152 | /// let fields = &ext |
153 | /// .get::<FormattedFields<N>>() |
154 | /// .expect("will never be `None`" ); |
155 | /// |
156 | /// // Skip formatting the fields if the span had no fields. |
157 | /// if !fields.is_empty() { |
158 | /// write!(writer, "{{{}}}" , fields)?; |
159 | /// } |
160 | /// write!(writer, ": " )?; |
161 | /// } |
162 | /// } |
163 | /// |
164 | /// // Write fields on the event |
165 | /// ctx.field_format().format_fields(writer.by_ref(), event)?; |
166 | /// |
167 | /// writeln!(writer) |
168 | /// } |
169 | /// } |
170 | /// |
171 | /// let _subscriber = tracing_subscriber::fmt() |
172 | /// .event_format(MyFormatter) |
173 | /// .init(); |
174 | /// |
175 | /// let _span = tracing::info_span!("my_span" , answer = 42).entered(); |
176 | /// tracing::info!(question = "life, the universe, and everything" , "hello world" ); |
177 | /// ``` |
178 | /// |
179 | /// This formatter will print events like this: |
180 | /// |
181 | /// ```text |
182 | /// DEBUG yak_shaving::shaver: some-span{field-on-span=foo}: started shaving yak |
183 | /// ``` |
184 | /// |
185 | /// [`layer::Context`]: crate::layer::Context |
186 | /// [`fmt::Layer`]: super::Layer |
187 | /// [`fmt::Subscriber`]: super::Subscriber |
188 | /// [`Event`]: tracing::Event |
189 | /// [implements `FormatFields`]: super::FmtContext#impl-FormatFields<'writer> |
190 | /// [ANSI terminal escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code |
191 | /// [`Writer::has_ansi_escapes`]: Writer::has_ansi_escapes |
192 | /// [`nu_ansi_term`]: https://crates.io/crates/nu_ansi_term |
193 | /// [`owo-colors`]: https://crates.io/crates/owo-colors |
194 | /// [default formatter]: Full |
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`]. |
201 | 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 | { |
215 | fn format_event( |
216 | &self, |
217 | ctx: &FmtContext<'_, S, N>, |
218 | writer: Writer<'_>, |
219 | event: &Event<'_>, |
220 | ) -> fmt::Result { |
221 | (*self)(ctx, writer, event) |
222 | } |
223 | } |
224 | /// A type that can format a [set of fields] to a [`Writer`]. |
225 | /// |
226 | /// `FormatFields` is primarily used in the context of [`FmtSubscriber`]. Each |
227 | /// time a span or event with fields is recorded, the subscriber will format |
228 | /// those fields with its associated `FormatFields` implementation. |
229 | /// |
230 | /// [set of fields]: crate::field::RecordFields |
231 | /// [`FmtSubscriber`]: super::Subscriber |
232 | pub trait FormatFields<'writer> { |
233 | /// Format the provided `fields` to the provided [`Writer`], returning a result. |
234 | fn format_fields<R: RecordFields>(&self, writer: Writer<'writer>, fields: R) -> fmt::Result; |
235 | |
236 | /// Record additional field(s) on an existing span. |
237 | /// |
238 | /// By default, this appends a space to the current set of fields if it is |
239 | /// non-empty, and then calls `self.format_fields`. If different behavior is |
240 | /// required, the default implementation of this method can be overridden. |
241 | fn add_fields( |
242 | &self, |
243 | current: &'writer mut FormattedFields<Self>, |
244 | fields: &span::Record<'_>, |
245 | ) -> fmt::Result { |
246 | if !current.fields.is_empty() { |
247 | current.fields.push(ch:' ' ); |
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 | /// ``` |
270 | 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" )))] |
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 | /// |
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'm gonna shave a yak </font><i>excitement</i><font color="#AAAAAA">="yay!" </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3 </font><font color="#AAAAAA"><i>yak</i></font><font color="#AAAAAA">=1</font> |
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'm gonna shave a yak </font><i>excitement</i><font color="#AAAAAA">="yay!" </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3 </font><font color="#AAAAAA"><i>yak</i></font><font color="#AAAAAA">=2</font> |
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'm gonna shave a yak </font><i>excitement</i><font color="#AAAAAA">="yay!" </font><font color="#AAAAAA"><i>yaks</i></font><font color="#AAAAAA">=3 </font><font color="#AAAAAA"><i>yak</i></font><font color="#AAAAAA">=3</font> |
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'm gonna shave a yak </font><i>excitement</i><font color="#AAAAAA">="yay!"</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'm gonna shave a yak </font><i>excitement</i><font color="#AAAAAA">="yay!"</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'm gonna shave a yak </font><i>excitement</i><font color="#AAAAAA">="yay!"</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...?) |
419 | 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? |
427 | 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. |
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 ] |
461 | 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 ] |
483 | 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 |
499 | 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 |
509 | pub fn has_ansi_escapes(&self) -> bool { |
510 | self.is_ansi |
511 | } |
512 | |
513 | 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 | |
524 | 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 | |
535 | 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 ] |
549 | fn write_str(&mut self, s: &str) -> fmt::Result { |
550 | Writer::write_str(self, s) |
551 | } |
552 | |
553 | #[inline ] |
554 | fn write_char(&mut self, c: char) -> fmt::Result { |
555 | Writer::write_char(self, c) |
556 | } |
557 | |
558 | #[inline ] |
559 | 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<'_> { |
565 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
566 | f&mut DebugStruct<'_, '_>.debug_struct("Writer" ) |
567 | .field("writer" , &format_args!("<&mut dyn fmt::Write>" )) |
568 | .field(name:"is_ansi" , &self.is_ansi) |
569 | .finish() |
570 | } |
571 | } |
572 | |
573 | // === impl Format === |
574 | |
575 | impl Default for Format<Full, SystemTime> { |
576 | 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`]. |
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" )))] |
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" )))] |
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 |
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. |
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. |
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. |
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. |
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 |
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 |
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 |
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 |
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. |
799 | 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 ] |
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" )))] |
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" )))] |
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" )))] |
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 | { |
890 | 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 | { |
1018 | 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 dimmed = writer.dimmed(); |
1086 | |
1087 | let mut needs_space = false; |
1088 | if self.display_target { |
1089 | write!(writer, " {}{}" , dimmed.paint(meta.target()), dimmed.paint(":" ))?; |
1090 | needs_space = true; |
1091 | } |
1092 | |
1093 | if self.display_filename { |
1094 | if let Some(filename) = meta.file() { |
1095 | if self.display_target { |
1096 | writer.write_char(' ' )?; |
1097 | } |
1098 | write!(writer, " {}{}" , dimmed.paint(filename), dimmed.paint(":" ))?; |
1099 | needs_space = true; |
1100 | } |
1101 | } |
1102 | |
1103 | if self.display_line_number { |
1104 | if let Some(line_number) = meta.line() { |
1105 | write!( |
1106 | writer, |
1107 | " {}{}{}{}" , |
1108 | dimmed.prefix(), |
1109 | line_number, |
1110 | dimmed.suffix(), |
1111 | dimmed.paint(":" ) |
1112 | )?; |
1113 | needs_space = true; |
1114 | } |
1115 | } |
1116 | |
1117 | if needs_space { |
1118 | writer.write_char(' ' )?; |
1119 | } |
1120 | |
1121 | ctx.format_fields(writer.by_ref(), event)?; |
1122 | |
1123 | for span in ctx |
1124 | .event_scope() |
1125 | .into_iter() |
1126 | .flat_map(crate::registry::Scope::from_root) |
1127 | { |
1128 | let exts = span.extensions(); |
1129 | if let Some(fields) = exts.get::<FormattedFields<N>>() { |
1130 | if !fields.is_empty() { |
1131 | write!(writer, " {}" , dimmed.paint(&fields.fields))?; |
1132 | } |
1133 | } |
1134 | } |
1135 | writeln!(writer) |
1136 | } |
1137 | } |
1138 | |
1139 | // === impl FormatFields === |
1140 | impl<'writer, M> FormatFields<'writer> for M |
1141 | where |
1142 | M: MakeOutput<Writer<'writer>, fmt::Result>, |
1143 | M::Visitor: VisitFmt + VisitOutput<fmt::Result>, |
1144 | { |
1145 | fn format_fields<R: RecordFields>(&self, writer: Writer<'writer>, fields: R) -> fmt::Result { |
1146 | let mut v: >>::Visitor = self.make_visitor(target:writer); |
1147 | fields.record(&mut v); |
1148 | v.finish() |
1149 | } |
1150 | } |
1151 | |
1152 | /// The default [`FormatFields`] implementation. |
1153 | /// |
1154 | #[derive (Debug)] |
1155 | pub struct DefaultFields { |
1156 | // reserve the ability to add fields to this without causing a breaking |
1157 | // change in the future. |
1158 | _private: (), |
1159 | } |
1160 | |
1161 | /// The [visitor] produced by [`DefaultFields`]'s [`MakeVisitor`] implementation. |
1162 | /// |
1163 | /// [visitor]: super::super::field::Visit |
1164 | /// [`MakeVisitor`]: super::super::field::MakeVisitor |
1165 | #[derive (Debug)] |
1166 | pub struct DefaultVisitor<'a> { |
1167 | writer: Writer<'a>, |
1168 | is_empty: bool, |
1169 | result: fmt::Result, |
1170 | } |
1171 | |
1172 | impl DefaultFields { |
1173 | /// Returns a new default [`FormatFields`] implementation. |
1174 | /// |
1175 | pub fn new() -> Self { |
1176 | Self { _private: () } |
1177 | } |
1178 | } |
1179 | |
1180 | impl Default for DefaultFields { |
1181 | fn default() -> Self { |
1182 | Self::new() |
1183 | } |
1184 | } |
1185 | |
1186 | impl<'a> MakeVisitor<Writer<'a>> for DefaultFields { |
1187 | type Visitor = DefaultVisitor<'a>; |
1188 | |
1189 | #[inline ] |
1190 | fn make_visitor(&self, target: Writer<'a>) -> Self::Visitor { |
1191 | DefaultVisitor::new(writer:target, is_empty:true) |
1192 | } |
1193 | } |
1194 | |
1195 | // === impl DefaultVisitor === |
1196 | |
1197 | impl<'a> DefaultVisitor<'a> { |
1198 | /// Returns a new default visitor that formats to the provided `writer`. |
1199 | /// |
1200 | /// # Arguments |
1201 | /// - `writer`: the writer to format to. |
1202 | /// - `is_empty`: whether or not any fields have been previously written to |
1203 | /// that writer. |
1204 | pub fn new(writer: Writer<'a>, is_empty: bool) -> Self { |
1205 | Self { |
1206 | writer, |
1207 | is_empty, |
1208 | result: Ok(()), |
1209 | } |
1210 | } |
1211 | |
1212 | fn maybe_pad(&mut self) { |
1213 | if self.is_empty { |
1214 | self.is_empty = false; |
1215 | } else { |
1216 | self.result = write!(self.writer, " " ); |
1217 | } |
1218 | } |
1219 | } |
1220 | |
1221 | impl<'a> field::Visit for DefaultVisitor<'a> { |
1222 | fn record_str(&mut self, field: &Field, value: &str) { |
1223 | if self.result.is_err() { |
1224 | return; |
1225 | } |
1226 | |
1227 | if field.name() == "message" { |
1228 | self.record_debug(field, &format_args!(" {}" , value)) |
1229 | } else { |
1230 | self.record_debug(field, &value) |
1231 | } |
1232 | } |
1233 | |
1234 | fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) { |
1235 | if let Some(source) = value.source() { |
1236 | let italic = self.writer.italic(); |
1237 | self.record_debug( |
1238 | field, |
1239 | &format_args!( |
1240 | " {} {}{}{}{}" , |
1241 | value, |
1242 | italic.paint(field.name()), |
1243 | italic.paint(".sources" ), |
1244 | self.writer.dimmed().paint("=" ), |
1245 | ErrorSourceList(source) |
1246 | ), |
1247 | ) |
1248 | } else { |
1249 | self.record_debug(field, &format_args!(" {}" , value)) |
1250 | } |
1251 | } |
1252 | |
1253 | fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { |
1254 | if self.result.is_err() { |
1255 | return; |
1256 | } |
1257 | |
1258 | self.maybe_pad(); |
1259 | self.result = match field.name() { |
1260 | "message" => write!(self.writer, " {:?}" , value), |
1261 | // Skip fields that are actually log metadata that have already been handled |
1262 | #[cfg (feature = "tracing-log" )] |
1263 | name if name.starts_with("log." ) => Ok(()), |
1264 | name if name.starts_with("r#" ) => write!( |
1265 | self.writer, |
1266 | " {}{}{:?}" , |
1267 | self.writer.italic().paint(&name[2..]), |
1268 | self.writer.dimmed().paint("=" ), |
1269 | value |
1270 | ), |
1271 | name => write!( |
1272 | self.writer, |
1273 | " {}{}{:?}" , |
1274 | self.writer.italic().paint(name), |
1275 | self.writer.dimmed().paint("=" ), |
1276 | value |
1277 | ), |
1278 | }; |
1279 | } |
1280 | } |
1281 | |
1282 | impl<'a> crate::field::VisitOutput<fmt::Result> for DefaultVisitor<'a> { |
1283 | fn finish(self) -> fmt::Result { |
1284 | self.result |
1285 | } |
1286 | } |
1287 | |
1288 | impl<'a> crate::field::VisitFmt for DefaultVisitor<'a> { |
1289 | fn writer(&mut self) -> &mut dyn fmt::Write { |
1290 | &mut self.writer |
1291 | } |
1292 | } |
1293 | |
1294 | /// Renders an error into a list of sources, *including* the error |
1295 | struct ErrorSourceList<'a>(&'a (dyn std::error::Error + 'static)); |
1296 | |
1297 | impl<'a> Display for ErrorSourceList<'a> { |
1298 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1299 | let mut list: DebugList<'_, '_> = f.debug_list(); |
1300 | let mut curr: Option<&dyn Error> = Some(self.0); |
1301 | while let Some(curr_err: &dyn Error) = curr { |
1302 | list.entry(&format_args!(" {}" , curr_err)); |
1303 | curr = curr_err.source(); |
1304 | } |
1305 | list.finish() |
1306 | } |
1307 | } |
1308 | |
1309 | struct FmtCtx<'a, S, N> { |
1310 | ctx: &'a FmtContext<'a, S, N>, |
1311 | span: Option<&'a span::Id>, |
1312 | #[cfg (feature = "ansi" )] |
1313 | ansi: bool, |
1314 | } |
1315 | |
1316 | impl<'a, S, N: 'a> FmtCtx<'a, S, N> |
1317 | where |
1318 | S: Subscriber + for<'lookup> LookupSpan<'lookup>, |
1319 | N: for<'writer> FormatFields<'writer> + 'static, |
1320 | { |
1321 | #[cfg (feature = "ansi" )] |
1322 | pub(crate) fn new( |
1323 | ctx: &'a FmtContext<'_, S, N>, |
1324 | span: Option<&'a span::Id>, |
1325 | ansi: bool, |
1326 | ) -> Self { |
1327 | Self { ctx, span, ansi } |
1328 | } |
1329 | |
1330 | #[cfg (not(feature = "ansi" ))] |
1331 | pub(crate) fn new(ctx: &'a FmtContext<'_, S, N>, span: Option<&'a span::Id>) -> Self { |
1332 | Self { ctx, span } |
1333 | } |
1334 | |
1335 | fn bold(&self) -> Style { |
1336 | #[cfg (feature = "ansi" )] |
1337 | { |
1338 | if self.ansi { |
1339 | return Style::new().bold(); |
1340 | } |
1341 | } |
1342 | |
1343 | Style::new() |
1344 | } |
1345 | } |
1346 | |
1347 | impl<'a, S, N: 'a> fmt::Display for FmtCtx<'a, S, N> |
1348 | where |
1349 | S: Subscriber + for<'lookup> LookupSpan<'lookup>, |
1350 | N: for<'writer> FormatFields<'writer> + 'static, |
1351 | { |
1352 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1353 | let bold: Style = self.bold(); |
1354 | let mut seen: bool = false; |
1355 | |
1356 | let span: Option> = self |
1357 | .span |
1358 | .and_then(|id: &Id| self.ctx.ctx.span(id)) |
1359 | .or_else(|| self.ctx.ctx.lookup_current()); |
1360 | |
1361 | let scope: impl Iterator- >
= span.into_iter().flat_map(|span: SpanRef<'_, S>| span.scope().from_root()); |
1362 | |
1363 | for span: SpanRef<'_, S> in scope { |
1364 | seen = true; |
1365 | write!(f, " {}:" , bold.paint(span.metadata().name()))?; |
1366 | } |
1367 | |
1368 | if seen { |
1369 | f.write_char(' ' )?; |
1370 | } |
1371 | Ok(()) |
1372 | } |
1373 | } |
1374 | |
1375 | #[cfg (not(feature = "ansi" ))] |
1376 | struct Style; |
1377 | |
1378 | #[cfg (not(feature = "ansi" ))] |
1379 | impl Style { |
1380 | fn new() -> Self { |
1381 | Style |
1382 | } |
1383 | |
1384 | fn bold(self) -> Self { |
1385 | self |
1386 | } |
1387 | |
1388 | fn paint(&self, d: impl fmt::Display) -> impl fmt::Display { |
1389 | d |
1390 | } |
1391 | |
1392 | fn prefix(&self) -> impl fmt::Display { |
1393 | "" |
1394 | } |
1395 | |
1396 | fn suffix(&self) -> impl fmt::Display { |
1397 | "" |
1398 | } |
1399 | } |
1400 | |
1401 | struct FmtThreadName<'a> { |
1402 | name: &'a str, |
1403 | } |
1404 | |
1405 | impl<'a> FmtThreadName<'a> { |
1406 | pub(crate) fn new(name: &'a str) -> Self { |
1407 | Self { name } |
1408 | } |
1409 | } |
1410 | |
1411 | impl<'a> fmt::Display for FmtThreadName<'a> { |
1412 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1413 | use std::sync::atomic::{ |
1414 | AtomicUsize, |
1415 | Ordering::{AcqRel, Acquire, Relaxed}, |
1416 | }; |
1417 | |
1418 | // Track the longest thread name length we've seen so far in an atomic, |
1419 | // so that it can be updated by any thread. |
1420 | static MAX_LEN: AtomicUsize = AtomicUsize::new(0); |
1421 | let len = self.name.len(); |
1422 | // Snapshot the current max thread name length. |
1423 | let mut max_len = MAX_LEN.load(Relaxed); |
1424 | |
1425 | while len > max_len { |
1426 | // Try to set a new max length, if it is still the value we took a |
1427 | // snapshot of. |
1428 | match MAX_LEN.compare_exchange(max_len, len, AcqRel, Acquire) { |
1429 | // We successfully set the new max value |
1430 | Ok(_) => break, |
1431 | // Another thread set a new max value since we last observed |
1432 | // it! It's possible that the new length is actually longer than |
1433 | // ours, so we'll loop again and check whether our length is |
1434 | // still the longest. If not, we'll just use the newer value. |
1435 | Err(actual) => max_len = actual, |
1436 | } |
1437 | } |
1438 | |
1439 | // pad thread name using `max_len` |
1440 | write!(f, " {:>width$}" , self.name, width = max_len) |
1441 | } |
1442 | } |
1443 | |
1444 | struct FmtLevel<'a> { |
1445 | level: &'a Level, |
1446 | #[cfg (feature = "ansi" )] |
1447 | ansi: bool, |
1448 | } |
1449 | |
1450 | impl<'a> FmtLevel<'a> { |
1451 | #[cfg (feature = "ansi" )] |
1452 | pub(crate) fn new(level: &'a Level, ansi: bool) -> Self { |
1453 | Self { level, ansi } |
1454 | } |
1455 | |
1456 | #[cfg (not(feature = "ansi" ))] |
1457 | pub(crate) fn new(level: &'a Level) -> Self { |
1458 | Self { level } |
1459 | } |
1460 | } |
1461 | |
1462 | const TRACE_STR: &str = "TRACE" ; |
1463 | const DEBUG_STR: &str = "DEBUG" ; |
1464 | const INFO_STR: &str = " INFO" ; |
1465 | const WARN_STR: &str = " WARN" ; |
1466 | const ERROR_STR: &str = "ERROR" ; |
1467 | |
1468 | #[cfg (not(feature = "ansi" ))] |
1469 | impl<'a> fmt::Display for FmtLevel<'a> { |
1470 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1471 | match *self.level { |
1472 | Level::TRACE => f.pad(TRACE_STR), |
1473 | Level::DEBUG => f.pad(DEBUG_STR), |
1474 | Level::INFO => f.pad(INFO_STR), |
1475 | Level::WARN => f.pad(WARN_STR), |
1476 | Level::ERROR => f.pad(ERROR_STR), |
1477 | } |
1478 | } |
1479 | } |
1480 | |
1481 | #[cfg (feature = "ansi" )] |
1482 | impl<'a> fmt::Display for FmtLevel<'a> { |
1483 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1484 | if self.ansi { |
1485 | match *self.level { |
1486 | Level::TRACE => write!(f, " {}" , Color::Purple.paint(TRACE_STR)), |
1487 | Level::DEBUG => write!(f, " {}" , Color::Blue.paint(DEBUG_STR)), |
1488 | Level::INFO => write!(f, " {}" , Color::Green.paint(INFO_STR)), |
1489 | Level::WARN => write!(f, " {}" , Color::Yellow.paint(WARN_STR)), |
1490 | Level::ERROR => write!(f, " {}" , Color::Red.paint(ERROR_STR)), |
1491 | } |
1492 | } else { |
1493 | match *self.level { |
1494 | Level::TRACE => f.pad(TRACE_STR), |
1495 | Level::DEBUG => f.pad(DEBUG_STR), |
1496 | Level::INFO => f.pad(INFO_STR), |
1497 | Level::WARN => f.pad(WARN_STR), |
1498 | Level::ERROR => f.pad(ERROR_STR), |
1499 | } |
1500 | } |
1501 | } |
1502 | } |
1503 | |
1504 | // === impl FieldFn === |
1505 | |
1506 | impl<'a, F> MakeVisitor<Writer<'a>> for FieldFn<F> |
1507 | where |
1508 | F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result + Clone, |
1509 | { |
1510 | type Visitor = FieldFnVisitor<'a, F>; |
1511 | |
1512 | fn make_visitor(&self, writer: Writer<'a>) -> Self::Visitor { |
1513 | FieldFnVisitor { |
1514 | writer, |
1515 | f: self.0.clone(), |
1516 | result: Ok(()), |
1517 | } |
1518 | } |
1519 | } |
1520 | |
1521 | impl<'a, F> Visit for FieldFnVisitor<'a, F> |
1522 | where |
1523 | F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result, |
1524 | { |
1525 | fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { |
1526 | if self.result.is_ok() { |
1527 | self.result = (self.f)(&mut self.writer, field, value) |
1528 | } |
1529 | } |
1530 | } |
1531 | |
1532 | impl<'a, F> VisitOutput<fmt::Result> for FieldFnVisitor<'a, F> |
1533 | where |
1534 | F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result, |
1535 | { |
1536 | fn finish(self) -> fmt::Result { |
1537 | self.result |
1538 | } |
1539 | } |
1540 | |
1541 | impl<'a, F> VisitFmt for FieldFnVisitor<'a, F> |
1542 | where |
1543 | F: Fn(&mut Writer<'a>, &Field, &dyn fmt::Debug) -> fmt::Result, |
1544 | { |
1545 | fn writer(&mut self) -> &mut dyn fmt::Write { |
1546 | &mut self.writer |
1547 | } |
1548 | } |
1549 | |
1550 | impl<'a, F> fmt::Debug for FieldFnVisitor<'a, F> { |
1551 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1552 | f&mut DebugStruct<'_, '_>.debug_struct("FieldFnVisitor" ) |
1553 | .field("f" , &format_args!(" {}" , std::any::type_name::<F>())) |
1554 | .field("writer" , &self.writer) |
1555 | .field(name:"result" , &self.result) |
1556 | .finish() |
1557 | } |
1558 | } |
1559 | |
1560 | // === printing synthetic Span events === |
1561 | |
1562 | /// Configures what points in the span lifecycle are logged as events. |
1563 | /// |
1564 | /// See also [`with_span_events`](super::SubscriberBuilder.html::with_span_events). |
1565 | #[derive (Clone, Eq, PartialEq, Ord, PartialOrd)] |
1566 | pub struct FmtSpan(u8); |
1567 | |
1568 | impl FmtSpan { |
1569 | /// one event when span is created |
1570 | pub const NEW: FmtSpan = FmtSpan(1 << 0); |
1571 | /// one event per enter of a span |
1572 | pub const ENTER: FmtSpan = FmtSpan(1 << 1); |
1573 | /// one event per exit of a span |
1574 | pub const EXIT: FmtSpan = FmtSpan(1 << 2); |
1575 | /// one event when the span is dropped |
1576 | pub const CLOSE: FmtSpan = FmtSpan(1 << 3); |
1577 | |
1578 | /// spans are ignored (this is the default) |
1579 | pub const NONE: FmtSpan = FmtSpan(0); |
1580 | /// one event per enter/exit of a span |
1581 | pub const ACTIVE: FmtSpan = FmtSpan(FmtSpan::ENTER.0 | FmtSpan::EXIT.0); |
1582 | /// events at all points (new, enter, exit, drop) |
1583 | pub const FULL: FmtSpan = |
1584 | FmtSpan(FmtSpan::NEW.0 | FmtSpan::ENTER.0 | FmtSpan::EXIT.0 | FmtSpan::CLOSE.0); |
1585 | |
1586 | /// Check whether or not a certain flag is set for this [`FmtSpan`] |
1587 | fn contains(&self, other: FmtSpan) -> bool { |
1588 | self.clone() & other.clone() == other |
1589 | } |
1590 | } |
1591 | |
1592 | macro_rules! impl_fmt_span_bit_op { |
1593 | ($trait:ident, $func:ident, $op:tt) => { |
1594 | impl std::ops::$trait for FmtSpan { |
1595 | type Output = FmtSpan; |
1596 | |
1597 | fn $func(self, rhs: Self) -> Self::Output { |
1598 | FmtSpan(self.0 $op rhs.0) |
1599 | } |
1600 | } |
1601 | }; |
1602 | } |
1603 | |
1604 | macro_rules! impl_fmt_span_bit_assign_op { |
1605 | ($trait:ident, $func:ident, $op:tt) => { |
1606 | impl std::ops::$trait for FmtSpan { |
1607 | fn $func(&mut self, rhs: Self) { |
1608 | *self = FmtSpan(self.0 $op rhs.0) |
1609 | } |
1610 | } |
1611 | }; |
1612 | } |
1613 | |
1614 | impl_fmt_span_bit_op!(BitAnd, bitand, &); |
1615 | impl_fmt_span_bit_op!(BitOr, bitor, |); |
1616 | impl_fmt_span_bit_op!(BitXor, bitxor, ^); |
1617 | |
1618 | impl_fmt_span_bit_assign_op!(BitAndAssign, bitand_assign, &); |
1619 | impl_fmt_span_bit_assign_op!(BitOrAssign, bitor_assign, |); |
1620 | impl_fmt_span_bit_assign_op!(BitXorAssign, bitxor_assign, ^); |
1621 | |
1622 | impl Debug for FmtSpan { |
1623 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1624 | let mut wrote_flag = false; |
1625 | let mut write_flags = |flag, flag_str| -> fmt::Result { |
1626 | if self.contains(flag) { |
1627 | if wrote_flag { |
1628 | f.write_str(" | " )?; |
1629 | } |
1630 | |
1631 | f.write_str(flag_str)?; |
1632 | wrote_flag = true; |
1633 | } |
1634 | |
1635 | Ok(()) |
1636 | }; |
1637 | |
1638 | if FmtSpan::NONE | self.clone() == FmtSpan::NONE { |
1639 | f.write_str("FmtSpan::NONE" )?; |
1640 | } else { |
1641 | write_flags(FmtSpan::NEW, "FmtSpan::NEW" )?; |
1642 | write_flags(FmtSpan::ENTER, "FmtSpan::ENTER" )?; |
1643 | write_flags(FmtSpan::EXIT, "FmtSpan::EXIT" )?; |
1644 | write_flags(FmtSpan::CLOSE, "FmtSpan::CLOSE" )?; |
1645 | } |
1646 | |
1647 | Ok(()) |
1648 | } |
1649 | } |
1650 | |
1651 | pub(super) struct FmtSpanConfig { |
1652 | pub(super) kind: FmtSpan, |
1653 | pub(super) fmt_timing: bool, |
1654 | } |
1655 | |
1656 | impl FmtSpanConfig { |
1657 | pub(super) fn without_time(self) -> Self { |
1658 | Self { |
1659 | kind: self.kind, |
1660 | fmt_timing: false, |
1661 | } |
1662 | } |
1663 | pub(super) fn with_kind(self, kind: FmtSpan) -> Self { |
1664 | Self { |
1665 | kind, |
1666 | fmt_timing: self.fmt_timing, |
1667 | } |
1668 | } |
1669 | pub(super) fn trace_new(&self) -> bool { |
1670 | self.kind.contains(FmtSpan::NEW) |
1671 | } |
1672 | pub(super) fn trace_enter(&self) -> bool { |
1673 | self.kind.contains(FmtSpan::ENTER) |
1674 | } |
1675 | pub(super) fn trace_exit(&self) -> bool { |
1676 | self.kind.contains(FmtSpan::EXIT) |
1677 | } |
1678 | pub(super) fn trace_close(&self) -> bool { |
1679 | self.kind.contains(FmtSpan::CLOSE) |
1680 | } |
1681 | } |
1682 | |
1683 | impl Debug for FmtSpanConfig { |
1684 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1685 | self.kind.fmt(f) |
1686 | } |
1687 | } |
1688 | |
1689 | impl Default for FmtSpanConfig { |
1690 | fn default() -> Self { |
1691 | Self { |
1692 | kind: FmtSpan::NONE, |
1693 | fmt_timing: true, |
1694 | } |
1695 | } |
1696 | } |
1697 | |
1698 | pub(super) struct TimingDisplay(pub(super) u64); |
1699 | impl Display for TimingDisplay { |
1700 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1701 | let mut t: f64 = self.0 as f64; |
1702 | for unit: &&str in ["ns" , "µs" , "ms" , "s" ].iter() { |
1703 | if t < 10.0 { |
1704 | return write!(f, " {:.2}{}" , t, unit); |
1705 | } else if t < 100.0 { |
1706 | return write!(f, " {:.1}{}" , t, unit); |
1707 | } else if t < 1000.0 { |
1708 | return write!(f, " {:.0}{}" , t, unit); |
1709 | } |
1710 | t /= 1000.0; |
1711 | } |
1712 | write!(f, " {:.0}s" , t * 1000.0) |
1713 | } |
1714 | } |
1715 | |
1716 | #[cfg (test)] |
1717 | pub(super) mod test { |
1718 | use crate::fmt::{test::MockMakeWriter, time::FormatTime}; |
1719 | use tracing::{ |
1720 | self, |
1721 | dispatcher::{set_default, Dispatch}, |
1722 | subscriber::with_default, |
1723 | }; |
1724 | |
1725 | use super::*; |
1726 | |
1727 | use regex::Regex; |
1728 | use std::{fmt, path::Path}; |
1729 | |
1730 | pub(crate) struct MockTime; |
1731 | impl FormatTime for MockTime { |
1732 | fn format_time(&self, w: &mut Writer<'_>) -> fmt::Result { |
1733 | write!(w, "fake time" ) |
1734 | } |
1735 | } |
1736 | |
1737 | #[test ] |
1738 | fn disable_everything() { |
1739 | // This test reproduces https://github.com/tokio-rs/tracing/issues/1354 |
1740 | let make_writer = MockMakeWriter::default(); |
1741 | let subscriber = crate::fmt::Subscriber::builder() |
1742 | .with_writer(make_writer.clone()) |
1743 | .without_time() |
1744 | .with_level(false) |
1745 | .with_target(false) |
1746 | .with_thread_ids(false) |
1747 | .with_thread_names(false); |
1748 | #[cfg (feature = "ansi" )] |
1749 | let subscriber = subscriber.with_ansi(false); |
1750 | assert_info_hello(subscriber, make_writer, "hello \n" ) |
1751 | } |
1752 | |
1753 | fn test_ansi<T>( |
1754 | is_ansi: bool, |
1755 | expected: &str, |
1756 | builder: crate::fmt::SubscriberBuilder<DefaultFields, Format<T>>, |
1757 | ) where |
1758 | Format<T, MockTime>: FormatEvent<crate::Registry, DefaultFields>, |
1759 | T: Send + Sync + 'static, |
1760 | { |
1761 | let make_writer = MockMakeWriter::default(); |
1762 | let subscriber = builder |
1763 | .with_writer(make_writer.clone()) |
1764 | .with_ansi(is_ansi) |
1765 | .with_timer(MockTime); |
1766 | run_test(subscriber, make_writer, expected) |
1767 | } |
1768 | |
1769 | #[cfg (not(feature = "ansi" ))] |
1770 | fn test_without_ansi<T>( |
1771 | expected: &str, |
1772 | builder: crate::fmt::SubscriberBuilder<DefaultFields, Format<T>>, |
1773 | ) where |
1774 | Format<T, MockTime>: FormatEvent<crate::Registry, DefaultFields>, |
1775 | T: Send + Sync, |
1776 | { |
1777 | let make_writer = MockMakeWriter::default(); |
1778 | let subscriber = builder.with_writer(make_writer).with_timer(MockTime); |
1779 | run_test(subscriber, make_writer, expected) |
1780 | } |
1781 | |
1782 | fn test_without_level<T>( |
1783 | expected: &str, |
1784 | builder: crate::fmt::SubscriberBuilder<DefaultFields, Format<T>>, |
1785 | ) where |
1786 | Format<T, MockTime>: FormatEvent<crate::Registry, DefaultFields>, |
1787 | T: Send + Sync + 'static, |
1788 | { |
1789 | let make_writer = MockMakeWriter::default(); |
1790 | let subscriber = builder |
1791 | .with_writer(make_writer.clone()) |
1792 | .with_level(false) |
1793 | .with_ansi(false) |
1794 | .with_timer(MockTime); |
1795 | run_test(subscriber, make_writer, expected); |
1796 | } |
1797 | |
1798 | #[test ] |
1799 | fn with_line_number_and_file_name() { |
1800 | let make_writer = MockMakeWriter::default(); |
1801 | let subscriber = crate::fmt::Subscriber::builder() |
1802 | .with_writer(make_writer.clone()) |
1803 | .with_file(true) |
1804 | .with_line_number(true) |
1805 | .with_level(false) |
1806 | .with_ansi(false) |
1807 | .with_timer(MockTime); |
1808 | |
1809 | let expected = Regex::new(&format!( |
1810 | "^fake time tracing_subscriber::fmt::format::test: {}:[0-9]+: hello \n$" , |
1811 | current_path() |
1812 | // if we're on Windows, the path might contain backslashes, which |
1813 | // have to be escpaed before compiling the regex. |
1814 | .replace(' \\' , " \\\\" ) |
1815 | )) |
1816 | .unwrap(); |
1817 | let _default = set_default(&subscriber.into()); |
1818 | tracing::info!("hello" ); |
1819 | let res = make_writer.get_string(); |
1820 | assert!(expected.is_match(&res)); |
1821 | } |
1822 | |
1823 | #[test ] |
1824 | fn with_line_number() { |
1825 | let make_writer = MockMakeWriter::default(); |
1826 | let subscriber = crate::fmt::Subscriber::builder() |
1827 | .with_writer(make_writer.clone()) |
1828 | .with_line_number(true) |
1829 | .with_level(false) |
1830 | .with_ansi(false) |
1831 | .with_timer(MockTime); |
1832 | |
1833 | let expected = |
1834 | Regex::new("^fake time tracing_subscriber::fmt::format::test: [0-9]+: hello \n$" ) |
1835 | .unwrap(); |
1836 | let _default = set_default(&subscriber.into()); |
1837 | tracing::info!("hello" ); |
1838 | let res = make_writer.get_string(); |
1839 | assert!(expected.is_match(&res)); |
1840 | } |
1841 | |
1842 | #[test ] |
1843 | fn with_filename() { |
1844 | let make_writer = MockMakeWriter::default(); |
1845 | let subscriber = crate::fmt::Subscriber::builder() |
1846 | .with_writer(make_writer.clone()) |
1847 | .with_file(true) |
1848 | .with_level(false) |
1849 | .with_ansi(false) |
1850 | .with_timer(MockTime); |
1851 | let expected = &format!( |
1852 | "fake time tracing_subscriber::fmt::format::test: {}: hello \n" , |
1853 | current_path(), |
1854 | ); |
1855 | assert_info_hello(subscriber, make_writer, expected); |
1856 | } |
1857 | |
1858 | #[test ] |
1859 | fn with_thread_ids() { |
1860 | let make_writer = MockMakeWriter::default(); |
1861 | let subscriber = crate::fmt::Subscriber::builder() |
1862 | .with_writer(make_writer.clone()) |
1863 | .with_thread_ids(true) |
1864 | .with_ansi(false) |
1865 | .with_timer(MockTime); |
1866 | let expected = |
1867 | "fake time INFO ThreadId(NUMERIC) tracing_subscriber::fmt::format::test: hello \n" ; |
1868 | |
1869 | assert_info_hello_ignore_numeric(subscriber, make_writer, expected); |
1870 | } |
1871 | |
1872 | #[test ] |
1873 | fn pretty_default() { |
1874 | let make_writer = MockMakeWriter::default(); |
1875 | let subscriber = crate::fmt::Subscriber::builder() |
1876 | .pretty() |
1877 | .with_writer(make_writer.clone()) |
1878 | .with_ansi(false) |
1879 | .with_timer(MockTime); |
1880 | let expected = format!( |
1881 | r#" fake time INFO tracing_subscriber::fmt::format::test: hello |
1882 | at {}:NUMERIC |
1883 | |
1884 | "# , |
1885 | file!() |
1886 | ); |
1887 | |
1888 | assert_info_hello_ignore_numeric(subscriber, make_writer, &expected) |
1889 | } |
1890 | |
1891 | fn assert_info_hello(subscriber: impl Into<Dispatch>, buf: MockMakeWriter, expected: &str) { |
1892 | let _default = set_default(&subscriber.into()); |
1893 | tracing::info!("hello" ); |
1894 | let result = buf.get_string(); |
1895 | |
1896 | assert_eq!(expected, result) |
1897 | } |
1898 | |
1899 | // When numeric characters are used they often form a non-deterministic value as they usually represent things like a thread id or line number. |
1900 | // This assert method should be used when non-deterministic numeric characters are present. |
1901 | fn assert_info_hello_ignore_numeric( |
1902 | subscriber: impl Into<Dispatch>, |
1903 | buf: MockMakeWriter, |
1904 | expected: &str, |
1905 | ) { |
1906 | let _default = set_default(&subscriber.into()); |
1907 | tracing::info!("hello" ); |
1908 | |
1909 | let regex = Regex::new("[0-9]+" ).unwrap(); |
1910 | let result = buf.get_string(); |
1911 | let result_cleaned = regex.replace_all(&result, "NUMERIC" ); |
1912 | |
1913 | assert_eq!(expected, result_cleaned) |
1914 | } |
1915 | |
1916 | fn test_overridden_parents<T>( |
1917 | expected: &str, |
1918 | builder: crate::fmt::SubscriberBuilder<DefaultFields, Format<T>>, |
1919 | ) where |
1920 | Format<T, MockTime>: FormatEvent<crate::Registry, DefaultFields>, |
1921 | T: Send + Sync + 'static, |
1922 | { |
1923 | let make_writer = MockMakeWriter::default(); |
1924 | let subscriber = builder |
1925 | .with_writer(make_writer.clone()) |
1926 | .with_level(false) |
1927 | .with_ansi(false) |
1928 | .with_timer(MockTime) |
1929 | .finish(); |
1930 | |
1931 | with_default(subscriber, || { |
1932 | let span1 = tracing::info_span!("span1" , span = 1); |
1933 | let span2 = tracing::info_span!(parent: &span1, "span2" , span = 2); |
1934 | tracing::info!(parent: &span2, "hello" ); |
1935 | }); |
1936 | assert_eq!(expected, make_writer.get_string()); |
1937 | } |
1938 | |
1939 | fn test_overridden_parents_in_scope<T>( |
1940 | expected1: &str, |
1941 | expected2: &str, |
1942 | builder: crate::fmt::SubscriberBuilder<DefaultFields, Format<T>>, |
1943 | ) where |
1944 | Format<T, MockTime>: FormatEvent<crate::Registry, DefaultFields>, |
1945 | T: Send + Sync + 'static, |
1946 | { |
1947 | let make_writer = MockMakeWriter::default(); |
1948 | let subscriber = builder |
1949 | .with_writer(make_writer.clone()) |
1950 | .with_level(false) |
1951 | .with_ansi(false) |
1952 | .with_timer(MockTime) |
1953 | .finish(); |
1954 | |
1955 | with_default(subscriber, || { |
1956 | let span1 = tracing::info_span!("span1" , span = 1); |
1957 | let span2 = tracing::info_span!(parent: &span1, "span2" , span = 2); |
1958 | let span3 = tracing::info_span!("span3" , span = 3); |
1959 | let _e3 = span3.enter(); |
1960 | |
1961 | tracing::info!("hello" ); |
1962 | assert_eq!(expected1, make_writer.get_string().as_str()); |
1963 | |
1964 | tracing::info!(parent: &span2, "hello" ); |
1965 | assert_eq!(expected2, make_writer.get_string().as_str()); |
1966 | }); |
1967 | } |
1968 | |
1969 | fn run_test(subscriber: impl Into<Dispatch>, buf: MockMakeWriter, expected: &str) { |
1970 | let _default = set_default(&subscriber.into()); |
1971 | tracing::info!("hello" ); |
1972 | assert_eq!(expected, buf.get_string()) |
1973 | } |
1974 | |
1975 | mod default { |
1976 | use super::*; |
1977 | |
1978 | #[test ] |
1979 | fn with_thread_ids() { |
1980 | let make_writer = MockMakeWriter::default(); |
1981 | let subscriber = crate::fmt::Subscriber::builder() |
1982 | .with_writer(make_writer.clone()) |
1983 | .with_thread_ids(true) |
1984 | .with_ansi(false) |
1985 | .with_timer(MockTime); |
1986 | let expected = |
1987 | "fake time INFO ThreadId(NUMERIC) tracing_subscriber::fmt::format::test: hello \n" ; |
1988 | |
1989 | assert_info_hello_ignore_numeric(subscriber, make_writer, expected); |
1990 | } |
1991 | |
1992 | #[cfg (feature = "ansi" )] |
1993 | #[test ] |
1994 | fn with_ansi_true() { |
1995 | 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" ; |
1996 | test_ansi(true, expected, crate::fmt::Subscriber::builder()); |
1997 | } |
1998 | |
1999 | #[cfg (feature = "ansi" )] |
2000 | #[test ] |
2001 | fn with_ansi_false() { |
2002 | let expected = "fake time INFO tracing_subscriber::fmt::format::test: hello \n" ; |
2003 | test_ansi(false, expected, crate::fmt::Subscriber::builder()); |
2004 | } |
2005 | |
2006 | #[cfg (not(feature = "ansi" ))] |
2007 | #[test ] |
2008 | fn without_ansi() { |
2009 | let expected = "fake time INFO tracing_subscriber::fmt::format::test: hello \n" ; |
2010 | test_without_ansi(expected, crate::fmt::Subscriber::builder()) |
2011 | } |
2012 | |
2013 | #[test ] |
2014 | fn without_level() { |
2015 | let expected = "fake time tracing_subscriber::fmt::format::test: hello \n" ; |
2016 | test_without_level(expected, crate::fmt::Subscriber::builder()) |
2017 | } |
2018 | |
2019 | #[test ] |
2020 | fn overridden_parents() { |
2021 | let expected = "fake time span1{span=1}:span2{span=2}: tracing_subscriber::fmt::format::test: hello \n" ; |
2022 | test_overridden_parents(expected, crate::fmt::Subscriber::builder()) |
2023 | } |
2024 | |
2025 | #[test ] |
2026 | fn overridden_parents_in_scope() { |
2027 | test_overridden_parents_in_scope( |
2028 | "fake time span3{span=3}: tracing_subscriber::fmt::format::test: hello \n" , |
2029 | "fake time span1{span=1}:span2{span=2}: tracing_subscriber::fmt::format::test: hello \n" , |
2030 | crate::fmt::Subscriber::builder(), |
2031 | ) |
2032 | } |
2033 | } |
2034 | |
2035 | mod compact { |
2036 | use super::*; |
2037 | |
2038 | #[cfg (feature = "ansi" )] |
2039 | #[test ] |
2040 | fn with_ansi_true() { |
2041 | let expected = " \u{1b}[2mfake time \u{1b}[0m \u{1b}[32m INFO \u{1b}[0m \u{1b}[2mtracing_subscriber::fmt::format::test \u{1b}[0m \u{1b}[2m: \u{1b}[0m hello \n" ; |
2042 | test_ansi(true, expected, crate::fmt::Subscriber::builder().compact()) |
2043 | } |
2044 | |
2045 | #[cfg (feature = "ansi" )] |
2046 | #[test ] |
2047 | fn with_ansi_false() { |
2048 | let expected = "fake time INFO tracing_subscriber::fmt::format::test: hello \n" ; |
2049 | test_ansi(false, expected, crate::fmt::Subscriber::builder().compact()); |
2050 | } |
2051 | |
2052 | #[cfg (not(feature = "ansi" ))] |
2053 | #[test ] |
2054 | fn without_ansi() { |
2055 | let expected = "fake time INFO tracing_subscriber::fmt::format::test: hello \n" ; |
2056 | test_without_ansi(expected, crate::fmt::Subscriber::builder().compact()) |
2057 | } |
2058 | |
2059 | #[test ] |
2060 | fn without_level() { |
2061 | let expected = "fake time tracing_subscriber::fmt::format::test: hello \n" ; |
2062 | test_without_level(expected, crate::fmt::Subscriber::builder().compact()); |
2063 | } |
2064 | |
2065 | #[test ] |
2066 | fn overridden_parents() { |
2067 | let expected = "fake time span1:span2: tracing_subscriber::fmt::format::test: hello span=1 span=2 \n" ; |
2068 | test_overridden_parents(expected, crate::fmt::Subscriber::builder().compact()) |
2069 | } |
2070 | |
2071 | #[test ] |
2072 | fn overridden_parents_in_scope() { |
2073 | test_overridden_parents_in_scope( |
2074 | "fake time span3: tracing_subscriber::fmt::format::test: hello span=3 \n" , |
2075 | "fake time span1:span2: tracing_subscriber::fmt::format::test: hello span=1 span=2 \n" , |
2076 | crate::fmt::Subscriber::builder().compact(), |
2077 | ) |
2078 | } |
2079 | } |
2080 | |
2081 | mod pretty { |
2082 | use super::*; |
2083 | |
2084 | #[test ] |
2085 | fn pretty_default() { |
2086 | let make_writer = MockMakeWriter::default(); |
2087 | let subscriber = crate::fmt::Subscriber::builder() |
2088 | .pretty() |
2089 | .with_writer(make_writer.clone()) |
2090 | .with_ansi(false) |
2091 | .with_timer(MockTime); |
2092 | let expected = format!( |
2093 | " fake time INFO tracing_subscriber::fmt::format::test: hello \n at {}:NUMERIC \n\n" , |
2094 | file!() |
2095 | ); |
2096 | |
2097 | assert_info_hello_ignore_numeric(subscriber, make_writer, &expected) |
2098 | } |
2099 | } |
2100 | |
2101 | #[test ] |
2102 | fn format_nanos() { |
2103 | fn fmt(t: u64) -> String { |
2104 | TimingDisplay(t).to_string() |
2105 | } |
2106 | |
2107 | assert_eq!(fmt(1), "1.00ns" ); |
2108 | assert_eq!(fmt(12), "12.0ns" ); |
2109 | assert_eq!(fmt(123), "123ns" ); |
2110 | assert_eq!(fmt(1234), "1.23µs" ); |
2111 | assert_eq!(fmt(12345), "12.3µs" ); |
2112 | assert_eq!(fmt(123456), "123µs" ); |
2113 | assert_eq!(fmt(1234567), "1.23ms" ); |
2114 | assert_eq!(fmt(12345678), "12.3ms" ); |
2115 | assert_eq!(fmt(123456789), "123ms" ); |
2116 | assert_eq!(fmt(1234567890), "1.23s" ); |
2117 | assert_eq!(fmt(12345678901), "12.3s" ); |
2118 | assert_eq!(fmt(123456789012), "123s" ); |
2119 | assert_eq!(fmt(1234567890123), "1235s" ); |
2120 | } |
2121 | |
2122 | #[test ] |
2123 | fn fmt_span_combinations() { |
2124 | let f = FmtSpan::NONE; |
2125 | assert!(!f.contains(FmtSpan::NEW)); |
2126 | assert!(!f.contains(FmtSpan::ENTER)); |
2127 | assert!(!f.contains(FmtSpan::EXIT)); |
2128 | assert!(!f.contains(FmtSpan::CLOSE)); |
2129 | |
2130 | let f = FmtSpan::ACTIVE; |
2131 | assert!(!f.contains(FmtSpan::NEW)); |
2132 | assert!(f.contains(FmtSpan::ENTER)); |
2133 | assert!(f.contains(FmtSpan::EXIT)); |
2134 | assert!(!f.contains(FmtSpan::CLOSE)); |
2135 | |
2136 | let f = FmtSpan::FULL; |
2137 | assert!(f.contains(FmtSpan::NEW)); |
2138 | assert!(f.contains(FmtSpan::ENTER)); |
2139 | assert!(f.contains(FmtSpan::EXIT)); |
2140 | assert!(f.contains(FmtSpan::CLOSE)); |
2141 | |
2142 | let f = FmtSpan::NEW | FmtSpan::CLOSE; |
2143 | assert!(f.contains(FmtSpan::NEW)); |
2144 | assert!(!f.contains(FmtSpan::ENTER)); |
2145 | assert!(!f.contains(FmtSpan::EXIT)); |
2146 | assert!(f.contains(FmtSpan::CLOSE)); |
2147 | } |
2148 | |
2149 | /// Returns the test's module path. |
2150 | fn current_path() -> String { |
2151 | Path::new("tracing-subscriber" ) |
2152 | .join("src" ) |
2153 | .join("fmt" ) |
2154 | .join("format" ) |
2155 | .join("mod.rs" ) |
2156 | .to_str() |
2157 | .expect("path must not contain invalid unicode" ) |
2158 | .to_owned() |
2159 | } |
2160 | } |
2161 | |