tracing_subscriber/fmt/
mod.rs

1//! A `Subscriber` for formatting and logging `tracing` data.
2//!
3//! # Overview
4//!
5//! [`tracing`] is a framework for instrumenting Rust programs with context-aware,
6//! structured, event-based diagnostic information. This crate provides an
7//! implementation of the [`Subscriber`] trait that records `tracing`'s `Event`s
8//! and `Span`s by formatting them as text and logging them to stdout.
9//!
10//! # Usage
11//!
12//! First, add this to your `Cargo.toml` file:
13//!
14//! ```toml
15//! [dependencies]
16//! tracing-subscriber = "0.3"
17//! ```
18//!
19//! *Compiler support: [requires `rustc` 1.65+][msrv]*
20//!
21//! [msrv]: super#supported-rust-versions
22//!
23//! Add the following to your executable to initialize the default subscriber:
24//! ```rust
25//! use tracing_subscriber;
26//!
27//! tracing_subscriber::fmt::init();
28//! ```
29//!
30//! ## Filtering Events with Environment Variables
31//!
32//! The default subscriber installed by `init` enables you to filter events
33//! at runtime using environment variables (using the [`EnvFilter`]).
34//!
35//! The filter syntax is a superset of the [`env_logger`] syntax.
36//!
37//! For example:
38//! - Setting `RUST_LOG=debug` enables all `Span`s and `Event`s
39//!   set to the log level `DEBUG` or higher
40//! - Setting `RUST_LOG=my_crate=trace` enables `Span`s and `Event`s
41//!   in `my_crate` at all log levels
42//!
43//! **Note**: This should **not** be called by libraries. Libraries should use
44//! [`tracing`] to publish `tracing` `Event`s.
45//!
46//! # Configuration
47//!
48//! You can configure a subscriber instead of using the defaults with
49//! the following functions:
50//!
51//! ### Subscriber
52//!
53//! The [`FmtSubscriber`] formats and records `tracing` events as line-oriented logs.
54//! You can create one by calling:
55//!
56//! ```rust
57//! let subscriber = tracing_subscriber::fmt()
58//!     // ... add configuration
59//!     .finish();
60//! ```
61//!
62//! You can find the configuration methods for [`FmtSubscriber`] in
63//! [`SubscriberBuilder`].
64//!
65//! ## Formatters
66//!
67//! The output format used by the layer and subscriber in this module is
68//! represented by implementing the [`FormatEvent`] trait, and can be
69//! customized. This module provides a number of formatter implementations:
70//!
71//! * [`format::Full`]: The default formatter. This emits human-readable,
72//!   single-line logs for each event that occurs, with the current span context
73//!   displayed before the formatted representation of the event. See
74//!   [here](format::Full#example-output) for sample output.
75//!
76//! * [`format::Compact`]: A variant of the default formatter, optimized for
77//!   short line lengths. Fields from the current span context are appended to
78//!   the fields of the formatted event. See
79//!   [here](format::Compact#example-output) for sample output.
80//!
81//! * [`format::Pretty`]: Emits excessively pretty, multi-line logs, optimized
82//!   for human readability. This is primarily intended to be used in local
83//!   development and debugging, or for command-line applications, where
84//!   automated analysis and compact storage of logs is less of a priority than
85//!   readability and visual appeal. See [here](format::Pretty#example-output)
86//!   for sample output.
87//!
88//! * [`format::Json`]: Outputs newline-delimited JSON logs. This is intended
89//!   for production use with systems where structured logs are consumed as JSON
90//!   by analysis and viewing tools. The JSON output is not optimized for human
91//!   readability. See [here](format::Json#example-output) for sample output.
92//!
93//! ### Customizing Formatters
94//!
95//! The formatting of log lines for spans and events is controlled by two
96//! traits, [`FormatEvent`] and [`FormatFields`]. The [`FormatEvent`] trait
97//! determines the overall formatting of the log line, such as what information
98//! from the event's metadata and span context is included and in what order.
99//! The [`FormatFields`] trait determines how fields — both the event's
100//! fields and fields on spans — are formatted.
101//!
102//! The [`fmt::format`] module provides several types which implement these traits,
103//! many of which expose additional configuration options to customize their
104//! output. The [`format::Format`] type implements common configuration used by
105//! all the formatters provided in this crate, and can be used as a builder to
106//! set specific formatting settings. For example:
107//!
108//! ```
109//! use tracing_subscriber::fmt;
110//!
111//! // Configure a custom event formatter
112//! let format = fmt::format()
113//!    .with_level(false) // don't include levels in formatted output
114//!    .with_target(false) // don't include targets
115//!    .with_thread_ids(true) // include the thread ID of the current thread
116//!    .with_thread_names(true) // include the name of the current thread
117//!    .compact(); // use the `Compact` formatting style.
118//!
119//! // Create a `fmt` subscriber that uses our custom event format, and set it
120//! // as the default.
121//! tracing_subscriber::fmt()
122//!     .event_format(format)
123//!     .init();
124//! ```
125//!
126//! However, if a specific output format is needed, other crates can
127//! also implement [`FormatEvent`] and [`FormatFields`]. See those traits'
128//! documentation for details on how to implement them.
129//!
130//! ## Filters
131//!
132//! If you want to filter the `tracing` `Events` based on environment
133//! variables, you can use the [`EnvFilter`] as follows:
134//!
135//! ```rust
136//! use tracing_subscriber::EnvFilter;
137//!
138//! let filter = EnvFilter::from_default_env();
139//! ```
140//!
141//! As mentioned above, the [`EnvFilter`] allows `Span`s and `Event`s to
142//! be filtered at runtime by setting the `RUST_LOG` environment variable.
143//!
144//! You can find the other available [`filter`]s in the documentation.
145//!
146//! ### Using Your Subscriber
147//!
148//! Finally, once you have configured your `Subscriber`, you need to
149//! configure your executable to use it.
150//!
151//! A subscriber can be installed globally using:
152//! ```rust
153//! use tracing;
154//! use tracing_subscriber::FmtSubscriber;
155//!
156//! let subscriber = FmtSubscriber::new();
157//!
158//! tracing::subscriber::set_global_default(subscriber)
159//!     .map_err(|_err| eprintln!("Unable to set global default subscriber"));
160//! // Note this will only fail if you try to set the global default
161//! // subscriber multiple times
162//! ```
163//!
164//! ### Composing Layers
165//!
166//! Composing an [`EnvFilter`] `Layer` and a [format `Layer`][super::fmt::Layer]:
167//!
168//! ```rust
169//! use tracing_subscriber::{fmt, EnvFilter};
170//! use tracing_subscriber::prelude::*;
171//!
172//! let fmt_layer = fmt::layer()
173//!     .with_target(false);
174//! let filter_layer = EnvFilter::try_from_default_env()
175//!     .or_else(|_| EnvFilter::try_new("info"))
176//!     .unwrap();
177//!
178//! tracing_subscriber::registry()
179//!     .with(filter_layer)
180//!     .with(fmt_layer)
181//!     .init();
182//! ```
183//!
184//! [`EnvFilter`]: super::filter::EnvFilter
185//! [`env_logger`]: https://docs.rs/env_logger/
186//! [`filter`]: super::filter
187//! [`FmtSubscriber`]: Subscriber
188//! [`Subscriber`]:
189//!     https://docs.rs/tracing/latest/tracing/trait.Subscriber.html
190//! [`tracing`]: https://crates.io/crates/tracing
191//! [`fmt::format`]: mod@crate::fmt::format
192
193use alloc::boxed::Box;
194use core::any::TypeId;
195use std::{error::Error, io};
196use tracing_core::{span, subscriber::Interest, Event, Metadata};
197
198mod fmt_layer;
199#[cfg_attr(docsrs, doc(cfg(all(feature = "fmt", feature = "std"))))]
200pub mod format;
201#[cfg_attr(docsrs, doc(cfg(all(feature = "fmt", feature = "std"))))]
202pub mod time;
203#[cfg_attr(docsrs, doc(cfg(all(feature = "fmt", feature = "std"))))]
204pub mod writer;
205
206pub use fmt_layer::{FmtContext, FormattedFields, Layer};
207
208use crate::layer::Layer as _;
209use crate::util::SubscriberInitExt;
210use crate::{
211    filter::LevelFilter,
212    layer,
213    registry::{LookupSpan, Registry},
214};
215
216#[doc(inline)]
217pub use self::{
218    format::{format, FormatEvent, FormatFields},
219    time::time,
220    writer::{MakeWriter, TestWriter},
221};
222
223/// A `Subscriber` that logs formatted representations of `tracing` events.
224///
225/// This consists of an inner `Formatter` wrapped in a layer that performs filtering.
226#[cfg_attr(docsrs, doc(cfg(all(feature = "fmt", feature = "std"))))]
227#[derive(Debug)]
228pub struct Subscriber<
229    N = format::DefaultFields,
230    E = format::Format<format::Full>,
231    F = LevelFilter,
232    W = fn() -> io::Stdout,
233> {
234    inner: layer::Layered<F, Formatter<N, E, W>>,
235}
236
237/// A `Subscriber` that logs formatted representations of `tracing` events.
238/// This type only logs formatted events; it does not perform any filtering.
239#[cfg_attr(docsrs, doc(cfg(all(feature = "fmt", feature = "std"))))]
240pub type Formatter<
241    N = format::DefaultFields,
242    E = format::Format<format::Full>,
243    W = fn() -> io::Stdout,
244> = layer::Layered<fmt_layer::Layer<Registry, N, E, W>, Registry>;
245
246/// Configures and constructs `Subscriber`s.
247#[cfg_attr(docsrs, doc(cfg(all(feature = "fmt", feature = "std"))))]
248#[derive(Debug)]
249#[must_use]
250pub struct SubscriberBuilder<
251    N = format::DefaultFields,
252    E = format::Format<format::Full>,
253    F = LevelFilter,
254    W = fn() -> io::Stdout,
255> {
256    filter: F,
257    inner: Layer<Registry, N, E, W>,
258}
259
260/// Returns a new [`SubscriberBuilder`] for configuring a [formatting subscriber].
261///
262/// This is essentially shorthand for [`SubscriberBuilder::default()]`.
263///
264/// # Examples
265///
266/// Using [`init`] to set the default subscriber:
267///
268/// ```rust
269/// tracing_subscriber::fmt().init();
270/// ```
271///
272/// Configuring the output format:
273///
274/// ```rust
275///
276/// tracing_subscriber::fmt()
277///     // Configure formatting settings.
278///     .with_target(false)
279///     .with_timer(tracing_subscriber::fmt::time::uptime())
280///     .with_level(true)
281///     // Set the subscriber as the default.
282///     .init();
283/// ```
284///
285/// [`try_init`] returns an error if the default subscriber could not be set:
286///
287/// ```rust
288/// use std::error::Error;
289///
290/// fn init_subscriber() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
291///     tracing_subscriber::fmt()
292///         // Configure the subscriber to emit logs in JSON format.
293///         .json()
294///         // Configure the subscriber to flatten event fields in the output JSON objects.
295///         .flatten_event(true)
296///         // Set the subscriber as the default, returning an error if this fails.
297///         .try_init()?;
298///
299///     Ok(())
300/// }
301/// ```
302///
303/// Rather than setting the subscriber as the default, [`finish`] _returns_ the
304/// constructed subscriber, which may then be passed to other functions:
305///
306/// ```rust
307/// let subscriber = tracing_subscriber::fmt()
308///     .with_max_level(tracing::Level::DEBUG)
309///     .compact()
310///     .finish();
311///
312/// tracing::subscriber::with_default(subscriber, || {
313///     // the subscriber will only be set as the default
314///     // inside this closure...
315/// })
316/// ```
317///
318/// [formatting subscriber]: Subscriber
319/// [`SubscriberBuilder::default()`]: SubscriberBuilder::default
320/// [`init`]: SubscriberBuilder::init()
321/// [`try_init`]: SubscriberBuilder::try_init()
322/// [`finish`]: SubscriberBuilder::finish()
323#[cfg_attr(docsrs, doc(cfg(all(feature = "fmt", feature = "std"))))]
324pub fn fmt() -> SubscriberBuilder {
325    SubscriberBuilder::default()
326}
327
328/// Returns a new [formatting layer] that can be [composed] with other layers to
329/// construct a [`Subscriber`].
330///
331/// This is a shorthand for the equivalent [`Layer::default()`] function.
332///
333/// [formatting layer]: Layer
334/// [composed]: crate::layer
335/// [`Layer::default()`]: Layer::default
336#[cfg_attr(docsrs, doc(cfg(all(feature = "fmt", feature = "std"))))]
337pub fn layer<S>() -> Layer<S> {
338    Layer::default()
339}
340
341impl Subscriber {
342    /// The maximum [verbosity level] that is enabled by a `Subscriber` by
343    /// default.
344    ///
345    /// This can be overridden with the [`SubscriberBuilder::with_max_level`] method.
346    ///
347    /// [verbosity level]: tracing_core::Level
348    /// [`SubscriberBuilder::with_max_level`]: SubscriberBuilder::with_max_level
349    pub const DEFAULT_MAX_LEVEL: LevelFilter = LevelFilter::INFO;
350
351    /// Returns a new `SubscriberBuilder` for configuring a format subscriber.
352    pub fn builder() -> SubscriberBuilder {
353        SubscriberBuilder::default()
354    }
355
356    /// Returns a new format subscriber with the default configuration.
357    pub fn new() -> Self {
358        Default::default()
359    }
360}
361
362impl Default for Subscriber {
363    fn default() -> Self {
364        SubscriberBuilder::default().finish()
365    }
366}
367
368// === impl Subscriber ===
369
370impl<N, E, F, W> tracing_core::Subscriber for Subscriber<N, E, F, W>
371where
372    N: for<'writer> FormatFields<'writer> + 'static,
373    E: FormatEvent<Registry, N> + 'static,
374    F: layer::Layer<Formatter<N, E, W>> + 'static,
375    W: for<'writer> MakeWriter<'writer> + 'static,
376    layer::Layered<F, Formatter<N, E, W>>: tracing_core::Subscriber,
377    fmt_layer::Layer<Registry, N, E, W>: layer::Layer<Registry>,
378{
379    #[inline]
380    fn register_callsite(&self, meta: &'static Metadata<'static>) -> Interest {
381        self.inner.register_callsite(meta)
382    }
383
384    #[inline]
385    fn enabled(&self, meta: &Metadata<'_>) -> bool {
386        self.inner.enabled(meta)
387    }
388
389    #[inline]
390    fn new_span(&self, attrs: &span::Attributes<'_>) -> span::Id {
391        self.inner.new_span(attrs)
392    }
393
394    #[inline]
395    fn record(&self, span: &span::Id, values: &span::Record<'_>) {
396        self.inner.record(span, values)
397    }
398
399    #[inline]
400    fn record_follows_from(&self, span: &span::Id, follows: &span::Id) {
401        self.inner.record_follows_from(span, follows)
402    }
403
404    #[inline]
405    fn event_enabled(&self, event: &Event<'_>) -> bool {
406        self.inner.event_enabled(event)
407    }
408
409    #[inline]
410    fn event(&self, event: &Event<'_>) {
411        self.inner.event(event);
412    }
413
414    #[inline]
415    fn enter(&self, id: &span::Id) {
416        // TODO: add on_enter hook
417        self.inner.enter(id);
418    }
419
420    #[inline]
421    fn exit(&self, id: &span::Id) {
422        self.inner.exit(id);
423    }
424
425    #[inline]
426    fn current_span(&self) -> span::Current {
427        self.inner.current_span()
428    }
429
430    #[inline]
431    fn clone_span(&self, id: &span::Id) -> span::Id {
432        self.inner.clone_span(id)
433    }
434
435    #[inline]
436    fn try_close(&self, id: span::Id) -> bool {
437        self.inner.try_close(id)
438    }
439
440    #[inline]
441    fn max_level_hint(&self) -> Option<tracing_core::LevelFilter> {
442        self.inner.max_level_hint()
443    }
444
445    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
446        if id == TypeId::of::<Self>() {
447            Some(self as *const Self as *const ())
448        } else {
449            unsafe { self.inner.downcast_raw(id) }
450        }
451    }
452}
453
454impl<'a, N, E, F, W> LookupSpan<'a> for Subscriber<N, E, F, W>
455where
456    layer::Layered<F, Formatter<N, E, W>>: LookupSpan<'a>,
457{
458    type Data = <layer::Layered<F, Formatter<N, E, W>> as LookupSpan<'a>>::Data;
459
460    fn span_data(&'a self, id: &span::Id) -> Option<Self::Data> {
461        self.inner.span_data(id)
462    }
463}
464
465// ===== impl SubscriberBuilder =====
466
467impl Default for SubscriberBuilder {
468    fn default() -> Self {
469        SubscriberBuilder {
470            filter: Subscriber::DEFAULT_MAX_LEVEL,
471            inner: Default::default(),
472        }
473        .log_internal_errors(true)
474    }
475}
476
477impl<N, E, F, W> SubscriberBuilder<N, E, F, W>
478where
479    N: for<'writer> FormatFields<'writer> + 'static,
480    E: FormatEvent<Registry, N> + 'static,
481    W: for<'writer> MakeWriter<'writer> + 'static,
482    F: layer::Layer<Formatter<N, E, W>> + Send + Sync + 'static,
483    fmt_layer::Layer<Registry, N, E, W>: layer::Layer<Registry> + Send + Sync + 'static,
484{
485    /// Finish the builder, returning a new `FmtSubscriber`.
486    pub fn finish(self) -> Subscriber<N, E, F, W> {
487        let subscriber = self.inner.with_subscriber(Registry::default());
488        Subscriber {
489            inner: self.filter.with_subscriber(subscriber),
490        }
491    }
492
493    /// Install this Subscriber as the global default if one is
494    /// not already set.
495    ///
496    /// If the `tracing-log` feature is enabled, this will also install
497    /// the LogTracer to convert `Log` records into `tracing` `Event`s.
498    ///
499    /// # Errors
500    /// Returns an Error if the initialization was unsuccessful, likely
501    /// because a global subscriber was already installed by another
502    /// call to `try_init`.
503    pub fn try_init(self) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
504        use crate::util::SubscriberInitExt;
505        self.finish().try_init()?;
506
507        Ok(())
508    }
509
510    /// Install this Subscriber as the global default.
511    ///
512    /// If the `tracing-log` feature is enabled, this will also install
513    /// the LogTracer to convert `Log` records into `tracing` `Event`s.
514    ///
515    /// # Panics
516    /// Panics if the initialization was unsuccessful, likely because a
517    /// global subscriber was already installed by another call to `try_init`.
518    pub fn init(self) {
519        self.try_init()
520            .expect("Unable to install global subscriber")
521    }
522}
523
524impl<N, E, F, W> From<SubscriberBuilder<N, E, F, W>> for tracing_core::Dispatch
525where
526    N: for<'writer> FormatFields<'writer> + 'static,
527    E: FormatEvent<Registry, N> + 'static,
528    W: for<'writer> MakeWriter<'writer> + 'static,
529    F: layer::Layer<Formatter<N, E, W>> + Send + Sync + 'static,
530    fmt_layer::Layer<Registry, N, E, W>: layer::Layer<Registry> + Send + Sync + 'static,
531{
532    fn from(builder: SubscriberBuilder<N, E, F, W>) -> tracing_core::Dispatch {
533        tracing_core::Dispatch::new(builder.finish())
534    }
535}
536
537impl<N, L, T, F, W> SubscriberBuilder<N, format::Format<L, T>, F, W>
538where
539    N: for<'writer> FormatFields<'writer> + 'static,
540{
541    /// Use the given [`timer`] for log message timestamps.
542    ///
543    /// See the [`time` module] for the provided timer implementations.
544    ///
545    /// Note that using the `"time`"" feature flag enables the
546    /// additional time formatters [`UtcTime`] and [`LocalTime`], which use the
547    /// [`time` crate] to provide more sophisticated timestamp formatting
548    /// options.
549    ///
550    /// [`timer`]: time::FormatTime
551    /// [`time` module]: mod@time
552    /// [`UtcTime`]: time::UtcTime
553    /// [`LocalTime`]: time::LocalTime
554    /// [`time` crate]: https://docs.rs/time/0.3
555    pub fn with_timer<T2>(self, timer: T2) -> SubscriberBuilder<N, format::Format<L, T2>, F, W> {
556        SubscriberBuilder {
557            filter: self.filter,
558            inner: self.inner.with_timer(timer),
559        }
560    }
561
562    /// Do not emit timestamps with log messages.
563    pub fn without_time(self) -> SubscriberBuilder<N, format::Format<L, ()>, F, W> {
564        SubscriberBuilder {
565            filter: self.filter,
566            inner: self.inner.without_time(),
567        }
568    }
569
570    /// Configures how synthesized events are emitted at points in the [span
571    /// lifecycle][lifecycle].
572    ///
573    /// The following options are available:
574    ///
575    /// - `FmtSpan::NONE`: No events will be synthesized when spans are
576    ///   created, entered, exited, or closed. Data from spans will still be
577    ///   included as the context for formatted events. This is the default.
578    /// - `FmtSpan::NEW`: An event will be synthesized when spans are created.
579    /// - `FmtSpan::ENTER`: An event will be synthesized when spans are entered.
580    /// - `FmtSpan::EXIT`: An event will be synthesized when spans are exited.
581    /// - `FmtSpan::CLOSE`: An event will be synthesized when a span closes. If
582    ///   [timestamps are enabled][time] for this formatter, the generated
583    ///   event will contain fields with the span's _busy time_ (the total
584    ///   time for which it was entered) and _idle time_ (the total time that
585    ///   the span existed but was not entered).
586    /// - `FmtSpan::ACTIVE`: An event will be synthesized when spans are entered
587    ///   or exited.
588    /// - `FmtSpan::FULL`: Events will be synthesized whenever a span is
589    ///   created, entered, exited, or closed. If timestamps are enabled, the
590    ///   close event will contain the span's busy and idle time, as
591    ///   described above.
592    ///
593    /// The options can be enabled in any combination. For instance, the following
594    /// will synthesize events whenever spans are created and closed:
595    ///
596    /// ```rust
597    /// use tracing_subscriber::fmt::format::FmtSpan;
598    /// use tracing_subscriber::fmt;
599    ///
600    /// let subscriber = fmt()
601    ///     .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
602    ///     .finish();
603    /// ```
604    ///
605    /// Note that the generated events will only be part of the log output by
606    /// this formatter; they will not be recorded by other `Subscriber`s or by
607    /// `Layer`s added to this subscriber.
608    ///
609    /// [lifecycle]: https://docs.rs/tracing/latest/tracing/span/index.html#the-span-lifecycle
610    /// [time]: SubscriberBuilder::without_time()
611    pub fn with_span_events(self, kind: format::FmtSpan) -> Self {
612        SubscriberBuilder {
613            inner: self.inner.with_span_events(kind),
614            ..self
615        }
616    }
617
618    /// Sets whether or not the formatter emits ANSI terminal escape codes
619    /// for colors and other text formatting.
620    ///
621    /// Enabling ANSI escapes (calling `with_ansi(true)`) requires the "ansi"
622    /// crate feature flag. Calling `with_ansi(true)` without the "ansi"
623    /// feature flag enabled will panic if debug assertions are enabled, or
624    /// print a warning otherwise.
625    ///
626    /// This method itself is still available without the feature flag. This
627    /// is to allow ANSI escape codes to be explicitly *disabled* without
628    /// having to opt-in to the dependencies required to emit ANSI formatting.
629    /// This way, code which constructs a formatter that should never emit
630    /// ANSI escape codes can ensure that they are not used, regardless of
631    /// whether or not other crates in the dependency graph enable the "ansi"
632    /// feature flag.
633    pub fn with_ansi(self, ansi: bool) -> SubscriberBuilder<N, format::Format<L, T>, F, W> {
634        SubscriberBuilder {
635            inner: self.inner.with_ansi(ansi),
636            ..self
637        }
638    }
639
640    /// Sets whether to write errors from [`FormatEvent`] to the writer.
641    /// Defaults to true.
642    ///
643    /// By default, `fmt::Layer` will write any `FormatEvent`-internal errors to
644    /// the writer. These errors are unlikely and will only occur if there is a
645    /// bug in the `FormatEvent` implementation or its dependencies.
646    ///
647    /// If writing to the writer fails, the error message is printed to stderr
648    /// as a fallback.
649    ///
650    /// [`FormatEvent`]: crate::fmt::FormatEvent
651    pub fn log_internal_errors(
652        self,
653        log_internal_errors: bool,
654    ) -> SubscriberBuilder<N, format::Format<L, T>, F, W> {
655        SubscriberBuilder {
656            inner: self.inner.log_internal_errors(log_internal_errors),
657            ..self
658        }
659    }
660
661    /// Sets whether or not an event's target is displayed.
662    pub fn with_target(
663        self,
664        display_target: bool,
665    ) -> SubscriberBuilder<N, format::Format<L, T>, F, W> {
666        SubscriberBuilder {
667            inner: self.inner.with_target(display_target),
668            ..self
669        }
670    }
671
672    /// Sets whether or not an event's [source code file path][file] is
673    /// displayed.
674    ///
675    /// [file]: tracing_core::Metadata::file
676    pub fn with_file(
677        self,
678        display_filename: bool,
679    ) -> SubscriberBuilder<N, format::Format<L, T>, F, W> {
680        SubscriberBuilder {
681            inner: self.inner.with_file(display_filename),
682            ..self
683        }
684    }
685
686    /// Sets whether or not an event's [source code line number][line] is
687    /// displayed.
688    ///
689    /// [line]: tracing_core::Metadata::line
690    pub fn with_line_number(
691        self,
692        display_line_number: bool,
693    ) -> SubscriberBuilder<N, format::Format<L, T>, F, W> {
694        SubscriberBuilder {
695            inner: self.inner.with_line_number(display_line_number),
696            ..self
697        }
698    }
699
700    /// Sets whether or not an event's level is displayed.
701    pub fn with_level(
702        self,
703        display_level: bool,
704    ) -> SubscriberBuilder<N, format::Format<L, T>, F, W> {
705        SubscriberBuilder {
706            inner: self.inner.with_level(display_level),
707            ..self
708        }
709    }
710
711    /// Sets whether or not the [name] of the current thread is displayed
712    /// when formatting events.
713    ///
714    /// [name]: std::thread#naming-threads
715    pub fn with_thread_names(
716        self,
717        display_thread_names: bool,
718    ) -> SubscriberBuilder<N, format::Format<L, T>, F, W> {
719        SubscriberBuilder {
720            inner: self.inner.with_thread_names(display_thread_names),
721            ..self
722        }
723    }
724
725    /// Sets whether or not the [thread ID] of the current thread is displayed
726    /// when formatting events.
727    ///
728    /// [thread ID]: std::thread::ThreadId
729    pub fn with_thread_ids(
730        self,
731        display_thread_ids: bool,
732    ) -> SubscriberBuilder<N, format::Format<L, T>, F, W> {
733        SubscriberBuilder {
734            inner: self.inner.with_thread_ids(display_thread_ids),
735            ..self
736        }
737    }
738
739    /// Sets the subscriber being built to use a less verbose formatter.
740    ///
741    /// See [`format::Compact`].
742    pub fn compact(self) -> SubscriberBuilder<N, format::Format<format::Compact, T>, F, W>
743    where
744        N: for<'writer> FormatFields<'writer> + 'static,
745    {
746        SubscriberBuilder {
747            filter: self.filter,
748            inner: self.inner.compact(),
749        }
750    }
751
752    /// Sets the subscriber being built to use an [excessively pretty, human-readable formatter](crate::fmt::format::Pretty).
753    #[cfg(feature = "ansi")]
754    #[cfg_attr(docsrs, doc(cfg(feature = "ansi")))]
755    pub fn pretty(
756        self,
757    ) -> SubscriberBuilder<format::Pretty, format::Format<format::Pretty, T>, F, W> {
758        SubscriberBuilder {
759            filter: self.filter,
760            inner: self.inner.pretty(),
761        }
762    }
763
764    /// Sets the subscriber being built to use a JSON formatter.
765    ///
766    /// See [`format::Json`] for details.
767    #[cfg(feature = "json")]
768    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
769    pub fn json(
770        self,
771    ) -> SubscriberBuilder<format::JsonFields, format::Format<format::Json, T>, F, W>
772    where
773        N: for<'writer> FormatFields<'writer> + 'static,
774    {
775        SubscriberBuilder {
776            filter: self.filter,
777            inner: self.inner.json(),
778        }
779    }
780}
781
782#[cfg(feature = "json")]
783#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
784impl<T, F, W> SubscriberBuilder<format::JsonFields, format::Format<format::Json, T>, F, W> {
785    /// Sets the json subscriber being built to flatten event metadata.
786    ///
787    /// See [`format::Json`] for details.
788    pub fn flatten_event(
789        self,
790        flatten_event: bool,
791    ) -> SubscriberBuilder<format::JsonFields, format::Format<format::Json, T>, F, W> {
792        SubscriberBuilder {
793            filter: self.filter,
794            inner: self.inner.flatten_event(flatten_event),
795        }
796    }
797
798    /// Sets whether or not the JSON subscriber being built will include the current span
799    /// in formatted events.
800    ///
801    /// See [`format::Json`] for details.
802    pub fn with_current_span(
803        self,
804        display_current_span: bool,
805    ) -> SubscriberBuilder<format::JsonFields, format::Format<format::Json, T>, F, W> {
806        SubscriberBuilder {
807            filter: self.filter,
808            inner: self.inner.with_current_span(display_current_span),
809        }
810    }
811
812    /// Sets whether or not the JSON subscriber being built will include a list (from
813    /// root to leaf) of all currently entered spans in formatted events.
814    ///
815    /// See [`format::Json`] for details.
816    pub fn with_span_list(
817        self,
818        display_span_list: bool,
819    ) -> SubscriberBuilder<format::JsonFields, format::Format<format::Json, T>, F, W> {
820        SubscriberBuilder {
821            filter: self.filter,
822            inner: self.inner.with_span_list(display_span_list),
823        }
824    }
825}
826
827#[cfg(feature = "env-filter")]
828#[cfg_attr(docsrs, doc(cfg(feature = "env-filter")))]
829impl<N, E, W> SubscriberBuilder<N, E, crate::EnvFilter, W>
830where
831    Formatter<N, E, W>: tracing_core::Subscriber + 'static,
832{
833    /// Configures the subscriber being built to allow filter reloading at
834    /// runtime.
835    pub fn with_filter_reloading(
836        self,
837    ) -> SubscriberBuilder<N, E, crate::reload::Layer<crate::EnvFilter, Formatter<N, E, W>>, W>
838    {
839        let (filter, _) = crate::reload::Layer::new(self.filter);
840        SubscriberBuilder {
841            filter,
842            inner: self.inner,
843        }
844    }
845}
846
847#[cfg(feature = "env-filter")]
848#[cfg_attr(docsrs, doc(cfg(feature = "env-filter")))]
849impl<N, E, W> SubscriberBuilder<N, E, crate::reload::Layer<crate::EnvFilter, Formatter<N, E, W>>, W>
850where
851    Formatter<N, E, W>: tracing_core::Subscriber + 'static,
852{
853    /// Returns a `Handle` that may be used to reload the constructed subscriber's
854    /// filter.
855    pub fn reload_handle(&self) -> crate::reload::Handle<crate::EnvFilter, Formatter<N, E, W>> {
856        self.filter.handle()
857    }
858}
859
860impl<N, E, F, W> SubscriberBuilder<N, E, F, W> {
861    /// Sets the field formatter that the subscriber being built will use to record
862    /// fields.
863    ///
864    /// For example:
865    /// ```rust
866    /// use tracing_subscriber::fmt::format;
867    /// use tracing_subscriber::prelude::*;
868    ///
869    /// let formatter =
870    ///     // Construct a custom formatter for `Debug` fields
871    ///     format::debug_fn(|writer, field, value| write!(writer, "{}: {:?}", field, value))
872    ///         // Use the `tracing_subscriber::MakeFmtExt` trait to wrap the
873    ///         // formatter so that a delimiter is added between fields.
874    ///         .delimited(", ");
875    ///
876    /// let subscriber = tracing_subscriber::fmt()
877    ///     .fmt_fields(formatter)
878    ///     .finish();
879    /// # drop(subscriber)
880    /// ```
881    pub fn fmt_fields<N2>(self, fmt_fields: N2) -> SubscriberBuilder<N2, E, F, W>
882    where
883        N2: for<'writer> FormatFields<'writer> + 'static,
884    {
885        SubscriberBuilder {
886            filter: self.filter,
887            inner: self.inner.fmt_fields(fmt_fields),
888        }
889    }
890
891    /// Sets the [`EnvFilter`] that the subscriber will use to determine if
892    /// a span or event is enabled.
893    ///
894    /// Note that this method requires the "env-filter" feature flag to be enabled.
895    ///
896    /// If a filter was previously set, or a maximum level was set by the
897    /// [`with_max_level`] method, that value is replaced by the new filter.
898    ///
899    /// # Examples
900    ///
901    /// Setting a filter based on the value of the `RUST_LOG` environment
902    /// variable:
903    /// ```rust
904    /// use tracing_subscriber::{fmt, EnvFilter};
905    ///
906    /// fmt()
907    ///     .with_env_filter(EnvFilter::from_default_env())
908    ///     .init();
909    /// ```
910    ///
911    /// Setting a filter based on a pre-set filter directive string:
912    /// ```rust
913    /// use tracing_subscriber::fmt;
914    ///
915    /// fmt()
916    ///     .with_env_filter("my_crate=info,my_crate::my_mod=debug,[my_span]=trace")
917    ///     .init();
918    /// ```
919    ///
920    /// Adding additional directives to a filter constructed from an env var:
921    /// ```rust
922    /// use tracing_subscriber::{fmt, filter::{EnvFilter, LevelFilter}};
923    ///
924    /// # fn filter() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
925    /// let filter = EnvFilter::try_from_env("MY_CUSTOM_FILTER_ENV_VAR")?
926    ///     // Set the base level when not matched by other directives to WARN.
927    ///     .add_directive(LevelFilter::WARN.into())
928    ///     // Set the max level for `my_crate::my_mod` to DEBUG, overriding
929    ///     // any directives parsed from the env variable.
930    ///     .add_directive("my_crate::my_mod=debug".parse()?);
931    ///
932    /// fmt()
933    ///     .with_env_filter(filter)
934    ///     .try_init()?;
935    /// # Ok(())}
936    /// ```
937    /// [`EnvFilter`]: super::filter::EnvFilter
938    /// [`with_max_level`]: SubscriberBuilder::with_max_level()
939    #[cfg(feature = "env-filter")]
940    #[cfg_attr(docsrs, doc(cfg(feature = "env-filter")))]
941    pub fn with_env_filter(
942        self,
943        filter: impl Into<crate::EnvFilter>,
944    ) -> SubscriberBuilder<N, E, crate::EnvFilter, W>
945    where
946        Formatter<N, E, W>: tracing_core::Subscriber + 'static,
947    {
948        let filter = filter.into();
949        SubscriberBuilder {
950            filter,
951            inner: self.inner,
952        }
953    }
954
955    /// Sets the maximum [verbosity level] that will be enabled by the
956    /// subscriber.
957    ///
958    /// If the max level has already been set, or a [`EnvFilter`] was added by
959    /// [`with_env_filter`], this replaces that configuration with the new
960    /// maximum level.
961    ///
962    /// # Examples
963    ///
964    /// Enable up to the `DEBUG` verbosity level:
965    /// ```rust
966    /// use tracing_subscriber::fmt;
967    /// use tracing::Level;
968    ///
969    /// fmt()
970    ///     .with_max_level(Level::DEBUG)
971    ///     .init();
972    /// ```
973    /// This subscriber won't record any spans or events!
974    /// ```rust
975    /// use tracing_subscriber::{fmt, filter::LevelFilter};
976    ///
977    /// let subscriber = fmt()
978    ///     .with_max_level(LevelFilter::OFF)
979    ///     .finish();
980    /// ```
981    /// [verbosity level]: tracing_core::Level
982    /// [`EnvFilter`]: struct@crate::filter::EnvFilter
983    /// [`with_env_filter`]: fn@Self::with_env_filter
984    pub fn with_max_level(
985        self,
986        filter: impl Into<LevelFilter>,
987    ) -> SubscriberBuilder<N, E, LevelFilter, W> {
988        let filter = filter.into();
989        SubscriberBuilder {
990            filter,
991            inner: self.inner,
992        }
993    }
994
995    /// Sets the [event formatter][`FormatEvent`] that the subscriber being built
996    /// will use to format events that occur.
997    ///
998    /// The event formatter may be any type implementing the [`FormatEvent`]
999    /// trait, which is implemented for all functions taking a [`FmtContext`], a
1000    /// [`Writer`], and an [`Event`].
1001    ///
1002    /// # Examples
1003    ///
1004    /// Setting a type implementing [`FormatEvent`] as the formatter:
1005    ///
1006    /// ```rust
1007    /// use tracing_subscriber::fmt::format;
1008    ///
1009    /// let subscriber = tracing_subscriber::fmt()
1010    ///     .event_format(format().compact())
1011    ///     .finish();
1012    /// ```
1013    ///
1014    /// [`Writer`]: struct@self::format::Writer
1015    pub fn event_format<E2>(self, fmt_event: E2) -> SubscriberBuilder<N, E2, F, W>
1016    where
1017        E2: FormatEvent<Registry, N> + 'static,
1018        N: for<'writer> FormatFields<'writer> + 'static,
1019        W: for<'writer> MakeWriter<'writer> + 'static,
1020    {
1021        SubscriberBuilder {
1022            filter: self.filter,
1023            inner: self.inner.event_format(fmt_event),
1024        }
1025    }
1026
1027    /// Sets the [`MakeWriter`] that the subscriber being built will use to write events.
1028    ///
1029    /// # Examples
1030    ///
1031    /// Using `stderr` rather than `stdout`:
1032    ///
1033    /// ```rust
1034    /// use tracing_subscriber::fmt;
1035    /// use std::io;
1036    ///
1037    /// fmt()
1038    ///     .with_writer(io::stderr)
1039    ///     .init();
1040    /// ```
1041    pub fn with_writer<W2>(self, make_writer: W2) -> SubscriberBuilder<N, E, F, W2>
1042    where
1043        W2: for<'writer> MakeWriter<'writer> + 'static,
1044    {
1045        SubscriberBuilder {
1046            filter: self.filter,
1047            inner: self.inner.with_writer(make_writer),
1048        }
1049    }
1050
1051    /// Configures the subscriber to support [`libtest`'s output capturing][capturing] when used in
1052    /// unit tests.
1053    ///
1054    /// See [`TestWriter`] for additional details.
1055    ///
1056    /// # Examples
1057    ///
1058    /// Using [`TestWriter`] to let `cargo test` capture test output. Note that we do not install it
1059    /// globally as it may cause conflicts.
1060    ///
1061    /// ```rust
1062    /// use tracing_subscriber::fmt;
1063    /// use tracing::subscriber;
1064    ///
1065    /// subscriber::set_default(
1066    ///     fmt()
1067    ///         .with_test_writer()
1068    ///         .finish()
1069    /// );
1070    /// ```
1071    ///
1072    /// [capturing]:
1073    /// https://doc.rust-lang.org/book/ch11-02-running-tests.html#showing-function-output
1074    /// [`TestWriter`]: writer::TestWriter
1075    pub fn with_test_writer(self) -> SubscriberBuilder<N, E, F, TestWriter> {
1076        SubscriberBuilder {
1077            filter: self.filter,
1078            inner: self.inner.with_writer(TestWriter::default()),
1079        }
1080    }
1081
1082    /// Updates the event formatter by applying a function to the existing event formatter.
1083    ///
1084    /// This sets the event formatter that the subscriber being built will use to record fields.
1085    ///
1086    /// # Examples
1087    ///
1088    /// Updating an event formatter:
1089    ///
1090    /// ```rust
1091    /// let subscriber = tracing_subscriber::fmt()
1092    ///     .map_event_format(|e| e.compact())
1093    ///     .finish();
1094    /// ```
1095    pub fn map_event_format<E2>(self, f: impl FnOnce(E) -> E2) -> SubscriberBuilder<N, E2, F, W>
1096    where
1097        E2: FormatEvent<Registry, N> + 'static,
1098        N: for<'writer> FormatFields<'writer> + 'static,
1099        W: for<'writer> MakeWriter<'writer> + 'static,
1100    {
1101        SubscriberBuilder {
1102            filter: self.filter,
1103            inner: self.inner.map_event_format(f),
1104        }
1105    }
1106
1107    /// Updates the field formatter by applying a function to the existing field formatter.
1108    ///
1109    /// This sets the field formatter that the subscriber being built will use to record fields.
1110    ///
1111    /// # Examples
1112    ///
1113    /// Updating a field formatter:
1114    ///
1115    /// ```rust
1116    /// use tracing_subscriber::field::MakeExt;
1117    /// let subscriber = tracing_subscriber::fmt()
1118    ///     .map_fmt_fields(|f| f.debug_alt())
1119    ///     .finish();
1120    /// ```
1121    pub fn map_fmt_fields<N2>(self, f: impl FnOnce(N) -> N2) -> SubscriberBuilder<N2, E, F, W>
1122    where
1123        N2: for<'writer> FormatFields<'writer> + 'static,
1124    {
1125        SubscriberBuilder {
1126            filter: self.filter,
1127            inner: self.inner.map_fmt_fields(f),
1128        }
1129    }
1130
1131    /// Updates the [`MakeWriter`] by applying a function to the existing [`MakeWriter`].
1132    ///
1133    /// This sets the [`MakeWriter`] that the subscriber being built will use to write events.
1134    ///
1135    /// # Examples
1136    ///
1137    /// Redirect output to stderr if level is <= WARN:
1138    ///
1139    /// ```rust
1140    /// use tracing::Level;
1141    /// use tracing_subscriber::fmt::{self, writer::MakeWriterExt};
1142    ///
1143    /// let stderr = std::io::stderr.with_max_level(Level::WARN);
1144    /// let layer = tracing_subscriber::fmt()
1145    ///     .map_writer(move |w| stderr.or_else(w))
1146    ///     .finish();
1147    /// ```
1148    pub fn map_writer<W2>(self, f: impl FnOnce(W) -> W2) -> SubscriberBuilder<N, E, F, W2>
1149    where
1150        W2: for<'writer> MakeWriter<'writer> + 'static,
1151    {
1152        SubscriberBuilder {
1153            filter: self.filter,
1154            inner: self.inner.map_writer(f),
1155        }
1156    }
1157}
1158
1159/// Install a global tracing subscriber that listens for events and
1160/// filters based on the value of the [`RUST_LOG` environment variable],
1161/// if one is not already set.
1162///
1163/// If the `tracing-log` feature is enabled, this will also install
1164/// the [`LogTracer`] to convert `log` records into `tracing` `Event`s.
1165///
1166/// This is shorthand for
1167///
1168/// ```rust
1169/// # fn doc() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
1170/// tracing_subscriber::fmt().try_init()
1171/// # }
1172/// ```
1173///
1174///
1175/// # Errors
1176///
1177/// Returns an Error if the initialization was unsuccessful,
1178/// likely because a global subscriber was already installed by another
1179/// call to `try_init`.
1180///
1181/// [`LogTracer`]:
1182///     https://docs.rs/tracing-log/0.1.0/tracing_log/struct.LogTracer.html
1183/// [`RUST_LOG` environment variable]: crate::filter::EnvFilter::DEFAULT_ENV
1184pub fn try_init() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
1185    let builder = Subscriber::builder();
1186
1187    #[cfg(feature = "env-filter")]
1188    let builder = builder.with_env_filter(crate::EnvFilter::from_default_env());
1189
1190    // If `env-filter` is disabled, remove the default max level filter from the
1191    // subscriber; it will be added to the `Targets` filter instead if no filter
1192    // is set in `RUST_LOG`.
1193    // Replacing the default `LevelFilter` with an `EnvFilter` would imply this,
1194    // but we can't replace the builder's filter with a `Targets` filter yet.
1195    #[cfg(not(feature = "env-filter"))]
1196    let builder = builder.with_max_level(LevelFilter::TRACE);
1197
1198    let subscriber = builder.finish();
1199    #[cfg(not(feature = "env-filter"))]
1200    let subscriber = {
1201        use crate::{filter::Targets, layer::SubscriberExt};
1202        use std::{env, eprintln, str::FromStr};
1203        let targets = match env::var("RUST_LOG") {
1204            Ok(var) => Targets::from_str(&var)
1205                .map_err(|e| {
1206                    eprintln!("Ignoring `RUST_LOG={:?}`: {}", var, e);
1207                })
1208                .unwrap_or_default(),
1209            Err(env::VarError::NotPresent) => {
1210                Targets::new().with_default(Subscriber::DEFAULT_MAX_LEVEL)
1211            }
1212            Err(e) => {
1213                eprintln!("Ignoring `RUST_LOG`: {}", e);
1214                Targets::new().with_default(Subscriber::DEFAULT_MAX_LEVEL)
1215            }
1216        };
1217        subscriber.with(targets)
1218    };
1219
1220    subscriber.try_init().map_err(Into::into)
1221}
1222
1223/// Install a global tracing subscriber that listens for events and
1224/// filters based on the value of the [`RUST_LOG` environment variable].
1225///
1226/// The configuration of the subscriber initialized by this function
1227/// depends on what [feature flags](crate#feature-flags) are enabled.
1228///
1229/// If the `tracing-log` feature is enabled, this will also install
1230/// the LogTracer to convert `Log` records into `tracing` `Event`s.
1231///
1232/// If the `env-filter` feature is enabled, this is shorthand for
1233///
1234/// ```rust
1235/// # use tracing_subscriber::EnvFilter;
1236/// tracing_subscriber::fmt()
1237///     .with_env_filter(EnvFilter::from_default_env())
1238///     .init();
1239/// ```
1240///
1241/// # Panics
1242/// Panics if the initialization was unsuccessful, likely because a
1243/// global subscriber was already installed by another call to `try_init`.
1244///
1245/// [`RUST_LOG` environment variable]: crate::filter::EnvFilter::DEFAULT_ENV
1246pub fn init() {
1247    try_init().expect("Unable to install global subscriber")
1248}
1249
1250#[cfg(test)]
1251mod test {
1252    use crate::{
1253        filter::LevelFilter,
1254        fmt::{
1255            format::{self, Format},
1256            time,
1257            writer::MakeWriter,
1258            Subscriber,
1259        },
1260    };
1261    use alloc::{borrow::ToOwned, string::String, vec::Vec};
1262    use std::{
1263        io,
1264        sync::{Arc, Mutex, MutexGuard, TryLockError},
1265    };
1266    use tracing_core::dispatcher::Dispatch;
1267
1268    pub(crate) struct MockWriter {
1269        buf: Arc<Mutex<Vec<u8>>>,
1270    }
1271
1272    impl MockWriter {
1273        pub(crate) fn new(buf: Arc<Mutex<Vec<u8>>>) -> Self {
1274            Self { buf }
1275        }
1276
1277        pub(crate) fn map_error<Guard>(err: TryLockError<Guard>) -> io::Error {
1278            match err {
1279                TryLockError::WouldBlock => io::Error::from(io::ErrorKind::WouldBlock),
1280                TryLockError::Poisoned(_) => io::Error::from(io::ErrorKind::Other),
1281            }
1282        }
1283
1284        pub(crate) fn buf(&self) -> io::Result<MutexGuard<'_, Vec<u8>>> {
1285            self.buf.try_lock().map_err(Self::map_error)
1286        }
1287    }
1288
1289    impl io::Write for MockWriter {
1290        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1291            self.buf()?.write(buf)
1292        }
1293
1294        fn flush(&mut self) -> io::Result<()> {
1295            self.buf()?.flush()
1296        }
1297    }
1298
1299    #[derive(Clone, Default)]
1300    pub(crate) struct MockMakeWriter {
1301        buf: Arc<Mutex<Vec<u8>>>,
1302    }
1303
1304    impl MockMakeWriter {
1305        pub(crate) fn new(buf: Arc<Mutex<Vec<u8>>>) -> Self {
1306            Self { buf }
1307        }
1308
1309        // this is currently only used by the JSON formatter tests. if we need
1310        // it elsewhere in the future, feel free to remove the `#[cfg]`
1311        // attribute!
1312        #[cfg(feature = "json")]
1313        pub(crate) fn buf(&self) -> MutexGuard<'_, Vec<u8>> {
1314            self.buf.lock().unwrap()
1315        }
1316
1317        pub(crate) fn get_string(&self) -> String {
1318            let mut buf = self.buf.lock().expect("lock shouldn't be poisoned");
1319            let string = std::str::from_utf8(&buf[..])
1320                .expect("formatter should not have produced invalid utf-8")
1321                .to_owned();
1322            buf.clear();
1323            string
1324        }
1325    }
1326
1327    impl<'a> MakeWriter<'a> for MockMakeWriter {
1328        type Writer = MockWriter;
1329
1330        fn make_writer(&'a self) -> Self::Writer {
1331            MockWriter::new(self.buf.clone())
1332        }
1333    }
1334
1335    #[test]
1336    fn impls() {
1337        let f = Format::default().with_timer(time::Uptime::default());
1338        let subscriber = Subscriber::builder().event_format(f).finish();
1339        let _dispatch = Dispatch::new(subscriber);
1340
1341        let f = format::Format::default();
1342        let subscriber = Subscriber::builder().event_format(f).finish();
1343        let _dispatch = Dispatch::new(subscriber);
1344
1345        let f = format::Format::default().compact();
1346        let subscriber = Subscriber::builder().event_format(f).finish();
1347        let _dispatch = Dispatch::new(subscriber);
1348    }
1349
1350    #[test]
1351    fn subscriber_downcasts() {
1352        let subscriber = Subscriber::builder().finish();
1353        let dispatch = Dispatch::new(subscriber);
1354        assert!(dispatch.downcast_ref::<Subscriber>().is_some());
1355    }
1356
1357    #[test]
1358    fn subscriber_downcasts_to_parts() {
1359        let subscriber = Subscriber::new();
1360        let dispatch = Dispatch::new(subscriber);
1361        assert!(dispatch.downcast_ref::<format::DefaultFields>().is_some());
1362        assert!(dispatch.downcast_ref::<LevelFilter>().is_some());
1363        assert!(dispatch.downcast_ref::<format::Format>().is_some())
1364    }
1365
1366    #[test]
1367    fn is_lookup_span() {
1368        fn assert_lookup_span<T: for<'a> crate::registry::LookupSpan<'a>>(_: T) {}
1369        let subscriber = Subscriber::new();
1370        assert_lookup_span(subscriber)
1371    }
1372}