tracing_subscriber/layer/
mod.rs

1//! The [`Layer`] trait, a composable abstraction for building [`Subscriber`]s.
2//!
3//! The [`Subscriber`] trait in `tracing-core` represents the _complete_ set of
4//! functionality required to consume `tracing` instrumentation. This means that
5//! a single `Subscriber` instance is a self-contained implementation of a
6//! complete strategy for collecting traces; but it _also_ means that the
7//! `Subscriber` trait cannot easily be composed with other `Subscriber`s.
8//!
9//! In particular, [`Subscriber`]s are responsible for generating [span IDs] and
10//! assigning them to spans. Since these IDs must uniquely identify a span
11//! within the context of the current trace, this means that there may only be
12//! a single `Subscriber` for a given thread at any point in time —
13//! otherwise, there would be no authoritative source of span IDs.
14//!
15//! On the other hand, the majority of the [`Subscriber`] trait's functionality
16//! is composable: any number of subscribers may _observe_ events, span entry
17//! and exit, and so on, provided that there is a single authoritative source of
18//! span IDs. The [`Layer`] trait represents this composable subset of the
19//! [`Subscriber`] behavior; it can _observe_ events and spans, but does not
20//! assign IDs.
21//!
22//! # Composing Layers
23//!
24//! Since a [`Layer`] does not implement a complete strategy for collecting
25//! traces, it must be composed with a `Subscriber` in order to be used. The
26//! [`Layer`] trait is generic over a type parameter (called `S` in the trait
27//! definition), representing the types of `Subscriber` they can be composed
28//! with. Thus, a [`Layer`] may be implemented that will only compose with a
29//! particular `Subscriber` implementation, or additional trait bounds may be
30//! added to constrain what types implementing `Subscriber` a `Layer` can wrap.
31//!
32//! `Layer`s may be added to a `Subscriber` by using the [`SubscriberExt::with`]
33//! method, which is provided by `tracing-subscriber`'s [prelude]. This method
34//! returns a [`Layered`] struct that implements `Subscriber` by composing the
35//! `Layer` with the `Subscriber`.
36//!
37//! For example:
38//! ```rust
39//! use tracing_subscriber::Layer;
40//! use tracing_subscriber::prelude::*;
41//! use tracing::Subscriber;
42//!
43//! pub struct MyLayer {
44//!     // ...
45//! }
46//!
47//! impl<S: Subscriber> Layer<S> for MyLayer {
48//!     // ...
49//! }
50//!
51//! pub struct MySubscriber {
52//!     // ...
53//! }
54//!
55//! # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
56//! impl Subscriber for MySubscriber {
57//!     // ...
58//! #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
59//! #   fn record(&self, _: &Id, _: &Record) {}
60//! #   fn event(&self, _: &Event) {}
61//! #   fn record_follows_from(&self, _: &Id, _: &Id) {}
62//! #   fn enabled(&self, _: &Metadata) -> bool { false }
63//! #   fn enter(&self, _: &Id) {}
64//! #   fn exit(&self, _: &Id) {}
65//! }
66//! # impl MyLayer {
67//! # fn new() -> Self { Self {} }
68//! # }
69//! # impl MySubscriber {
70//! # fn new() -> Self { Self { }}
71//! # }
72//!
73//! let subscriber = MySubscriber::new()
74//!     .with(MyLayer::new());
75//!
76//! tracing::subscriber::set_global_default(subscriber);
77//! ```
78//!
79//! Multiple `Layer`s may be composed in the same manner:
80//! ```rust
81//! # use tracing_subscriber::{Layer, layer::SubscriberExt};
82//! # use tracing::Subscriber;
83//! pub struct MyOtherLayer {
84//!     // ...
85//! }
86//!
87//! impl<S: Subscriber> Layer<S> for MyOtherLayer {
88//!     // ...
89//! }
90//!
91//! pub struct MyThirdLayer {
92//!     // ...
93//! }
94//!
95//! impl<S: Subscriber> Layer<S> for MyThirdLayer {
96//!     // ...
97//! }
98//! # pub struct MyLayer {}
99//! # impl<S: Subscriber> Layer<S> for MyLayer {}
100//! # pub struct MySubscriber { }
101//! # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
102//! # impl Subscriber for MySubscriber {
103//! #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
104//! #   fn record(&self, _: &Id, _: &Record) {}
105//! #   fn event(&self, _: &Event) {}
106//! #   fn record_follows_from(&self, _: &Id, _: &Id) {}
107//! #   fn enabled(&self, _: &Metadata) -> bool { false }
108//! #   fn enter(&self, _: &Id) {}
109//! #   fn exit(&self, _: &Id) {}
110//! }
111//! # impl MyLayer {
112//! # fn new() -> Self { Self {} }
113//! # }
114//! # impl MyOtherLayer {
115//! # fn new() -> Self { Self {} }
116//! # }
117//! # impl MyThirdLayer {
118//! # fn new() -> Self { Self {} }
119//! # }
120//! # impl MySubscriber {
121//! # fn new() -> Self { Self { }}
122//! # }
123//!
124//! let subscriber = MySubscriber::new()
125//!     .with(MyLayer::new())
126//!     .with(MyOtherLayer::new())
127//!     .with(MyThirdLayer::new());
128//!
129//! tracing::subscriber::set_global_default(subscriber);
130//! ```
131//!
132//! The [`Layer::with_subscriber`] constructs the [`Layered`] type from a
133//! [`Layer`] and [`Subscriber`], and is called by [`SubscriberExt::with`]. In
134//! general, it is more idiomatic to use [`SubscriberExt::with`], and treat
135//! [`Layer::with_subscriber`] as an implementation detail, as `with_subscriber`
136//! calls must be nested, leading to less clear code for the reader.
137//!
138//! ## Runtime Configuration With `Layer`s
139//!
140//! In some cases, a particular [`Layer`] may be enabled or disabled based on
141//! runtime configuration. This can introduce challenges, because the type of a
142//! layered [`Subscriber`] depends on which layers are added to it: if an `if`
143//! or `match` expression adds some [`Layer`] implementation in one branch,
144//! and other layers in another, the [`Subscriber`] values returned by those
145//! branches will have different types. For example, the following _will not_
146//! work:
147//!
148//! ```compile_fail
149//! # fn docs() -> Result<(), Box<dyn std::error::Error + 'static>> {
150//! # struct Config {
151//! #    is_prod: bool,
152//! #    path: &'static str,
153//! # }
154//! # let cfg = Config { is_prod: false, path: "debug.log" };
155//! use std::fs::File;
156//! use tracing_subscriber::{Registry, prelude::*};
157//!
158//! let stdout_log = tracing_subscriber::fmt::layer().pretty();
159//! let subscriber = Registry::default().with(stdout_log);
160//!
161//! // The compile error will occur here because the if and else
162//! // branches have different (and therefore incompatible) types.
163//! let subscriber = if cfg.is_prod {
164//!     let file = File::create(cfg.path)?;
165//!     let layer = tracing_subscriber::fmt::layer()
166//!         .json()
167//!         .with_writer(Arc::new(file));
168//!     layer.with(subscriber)
169//! } else {
170//!     layer
171//! };
172//!
173//! tracing::subscriber::set_global_default(subscriber)
174//!     .expect("Unable to set global subscriber");
175//! # Ok(()) }
176//! ```
177//!
178//! However, a [`Layer`] wrapped in an [`Option`] [also implements the `Layer`
179//! trait][option-impl]. This allows individual layers to be enabled or disabled at
180//! runtime while always producing a [`Subscriber`] of the same type. For
181//! example:
182//!
183//! ```
184//! # fn docs() -> Result<(), Box<dyn std::error::Error + 'static>> {
185//! # struct Config {
186//! #    is_prod: bool,
187//! #    path: &'static str,
188//! # }
189//! # let cfg = Config { is_prod: false, path: "debug.log" };
190//! use std::fs::File;
191//! use tracing_subscriber::{Registry, prelude::*};
192//!
193//! let stdout_log = tracing_subscriber::fmt::layer().pretty();
194//! let subscriber = Registry::default().with(stdout_log);
195//!
196//! // if `cfg.is_prod` is true, also log JSON-formatted logs to a file.
197//! let json_log = if cfg.is_prod {
198//!     let file = File::create(cfg.path)?;
199//!     let json_log = tracing_subscriber::fmt::layer()
200//!         .json()
201//!         .with_writer(file);
202//!     Some(json_log)
203//! } else {
204//!     None
205//! };
206//!
207//! // If `cfg.is_prod` is false, then `json` will be `None`, and this layer
208//! // will do nothing. However, the subscriber will still have the same type
209//! // regardless of whether the `Option`'s value is `None` or `Some`.
210//! let subscriber = subscriber.with(json_log);
211//!
212//! tracing::subscriber::set_global_default(subscriber)
213//!    .expect("Unable to set global subscriber");
214//! # Ok(()) }
215//! ```
216//!
217//! If a [`Layer`] may be one of several different types, note that [`Box<dyn
218//! Layer<S> + Send + Sync>` implements `Layer`][box-impl].
219//! This may be used to erase the type of a [`Layer`].
220//!
221//! For example, a function that configures a [`Layer`] to log to one of
222//! several outputs might return a `Box<dyn Layer<S> + Send + Sync + 'static>`:
223//! ```
224//! use tracing_subscriber::{
225//!     Layer,
226//!     registry::LookupSpan,
227//!     prelude::*,
228//! };
229//! use std::{path::PathBuf, fs::File, io};
230//!
231//! /// Configures whether logs are emitted to a file, to stdout, or to stderr.
232//! pub enum LogConfig {
233//!     File(PathBuf),
234//!     Stdout,
235//!     Stderr,
236//! }
237//!
238//! impl LogConfig {
239//!     pub fn layer<S>(self) -> Box<dyn Layer<S> + Send + Sync + 'static>
240//!     where
241//!         S: tracing_core::Subscriber,
242//!         for<'a> S: LookupSpan<'a>,
243//!     {
244//!         // Shared configuration regardless of where logs are output to.
245//!         let fmt = tracing_subscriber::fmt::layer()
246//!             .with_target(true)
247//!             .with_thread_names(true);
248//!
249//!         // Configure the writer based on the desired log target:
250//!         match self {
251//!             LogConfig::File(path) => {
252//!                 let file = File::create(path).expect("failed to create log file");
253//!                 Box::new(fmt.with_writer(file))
254//!             },
255//!             LogConfig::Stdout => Box::new(fmt.with_writer(io::stdout)),
256//!             LogConfig::Stderr => Box::new(fmt.with_writer(io::stderr)),
257//!         }
258//!     }
259//! }
260//!
261//! let config = LogConfig::Stdout;
262//! tracing_subscriber::registry()
263//!     .with(config.layer())
264//!     .init();
265//! ```
266//!
267//! The [`Layer::boxed`] method is provided to make boxing a `Layer`
268//! more convenient, but [`Box::new`] may be used as well.
269//!
270//! When the number of `Layer`s varies at runtime, note that a
271//! [`Vec<L> where L: Layer` also implements `Layer`][vec-impl]. This
272//! can be used to add a variable number of `Layer`s to a `Subscriber`:
273//!
274//! ```
275//! use tracing_subscriber::{Layer, prelude::*};
276//! struct MyLayer {
277//!     // ...
278//! }
279//! # impl MyLayer { fn new() -> Self { Self {} }}
280//!
281//! impl<S: tracing_core::Subscriber> Layer<S> for MyLayer {
282//!     // ...
283//! }
284//!
285//! /// Returns how many layers we need
286//! fn how_many_layers() -> usize {
287//!     // ...
288//!     # 3
289//! }
290//!
291//! // Create a variable-length `Vec` of layers
292//! let mut layers = Vec::new();
293//! for _ in 0..how_many_layers() {
294//!     layers.push(MyLayer::new());
295//! }
296//!
297//! tracing_subscriber::registry()
298//!     .with(layers)
299//!     .init();
300//! ```
301//!
302//! If a variable number of `Layer` is needed and those `Layer`s have
303//! different types, a `Vec` of [boxed `Layer` trait objects][box-impl] may
304//! be used. For example:
305//!
306//! ```
307//! use tracing_subscriber::{filter::LevelFilter, Layer, prelude::*};
308//! use std::fs::File;
309//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
310//! struct Config {
311//!     enable_log_file: bool,
312//!     enable_stdout: bool,
313//!     enable_stderr: bool,
314//!     // ...
315//! }
316//! # impl Config {
317//! #    fn from_config_file()-> Result<Self, Box<dyn std::error::Error>> {
318//! #         // don't enable the log file so that the example doesn't actually create it
319//! #         Ok(Self { enable_log_file: false, enable_stdout: true, enable_stderr: true })
320//! #    }
321//! # }
322//!
323//! let cfg = Config::from_config_file()?;
324//!
325//! // Based on our dynamically loaded config file, create any number of layers:
326//! let mut layers = Vec::new();
327//!
328//! if cfg.enable_log_file {
329//!     let file = File::create("myapp.log")?;
330//!     let layer = tracing_subscriber::fmt::layer()
331//!         .with_thread_names(true)
332//!         .with_target(true)
333//!         .json()
334//!         .with_writer(file)
335//!         // Box the layer as a type-erased trait object, so that it can
336//!         // be pushed to the `Vec`.
337//!         .boxed();
338//!     layers.push(layer);
339//! }
340//!
341//! if cfg.enable_stdout {
342//!     let layer = tracing_subscriber::fmt::layer()
343//!         .pretty()
344//!         .with_filter(LevelFilter::INFO)
345//!         // Box the layer as a type-erased trait object, so that it can
346//!         // be pushed to the `Vec`.
347//!         .boxed();
348//!     layers.push(layer);
349//! }
350//!
351//! if cfg.enable_stdout {
352//!     let layer = tracing_subscriber::fmt::layer()
353//!         .with_target(false)
354//!         .with_filter(LevelFilter::WARN)
355//!         // Box the layer as a type-erased trait object, so that it can
356//!         // be pushed to the `Vec`.
357//!         .boxed();
358//!     layers.push(layer);
359//! }
360//!
361//! tracing_subscriber::registry()
362//!     .with(layers)
363//!     .init();
364//!# Ok(()) }
365//! ```
366//!
367//! Finally, if the number of layers _changes_ at runtime, a `Vec` of
368//! subscribers can be used alongside the [`reload`](crate::reload) module to
369//! add or remove subscribers dynamically at runtime.
370//!
371//! [option-impl]: Layer#impl-Layer<S>-for-Option<L>
372//! [box-impl]: Layer#impl-Layer%3CS%3E-for-Box%3Cdyn%20Layer%3CS%3E%20+%20Send%20+%20Sync%3E
373//! [vec-impl]: Layer#impl-Layer<S>-for-Vec<L>
374//! [prelude]: crate::prelude
375//!
376//! # Recording Traces
377//!
378//! The [`Layer`] trait defines a set of methods for consuming notifications from
379//! tracing instrumentation, which are generally equivalent to the similarly
380//! named methods on [`Subscriber`]. Unlike [`Subscriber`], the methods on
381//! `Layer` are additionally passed a [`Context`] type, which exposes additional
382//! information provided by the wrapped subscriber (such as [the current span])
383//! to the layer.
384//!
385//! # Filtering with `Layer`s
386//!
387//! As well as strategies for handling trace events, the `Layer` trait may also
388//! be used to represent composable _filters_. This allows the determination of
389//! what spans and events should be recorded to be decoupled from _how_ they are
390//! recorded: a filtering layer can be applied to other layers or
391//! subscribers. `Layer`s can be used to implement _global filtering_, where a
392//! `Layer` provides a filtering strategy for the entire subscriber.
393//! Additionally, individual recording `Layer`s or sets of `Layer`s may be
394//! combined with _per-layer filters_ that control what spans and events are
395//! recorded by those layers.
396//!
397//! ## Global Filtering
398//!
399//! A `Layer` that implements a filtering strategy should override the
400//! [`register_callsite`] and/or [`enabled`] methods. It may also choose to implement
401//! methods such as [`on_enter`], if it wishes to filter trace events based on
402//! the current span context.
403//!
404//! Note that the [`Layer::register_callsite`] and [`Layer::enabled`] methods
405//! determine whether a span or event is enabled *globally*. Thus, they should
406//! **not** be used to indicate whether an individual layer wishes to record a
407//! particular span or event. Instead, if a layer is only interested in a subset
408//! of trace data, but does *not* wish to disable other spans and events for the
409//! rest of the layer stack should ignore those spans and events in its
410//! notification methods.
411//!
412//! The filtering methods on a stack of `Layer`s are evaluated in a top-down
413//! order, starting with the outermost `Layer` and ending with the wrapped
414//! [`Subscriber`]. If any layer returns `false` from its [`enabled`] method, or
415//! [`Interest::never()`] from its [`register_callsite`] method, filter
416//! evaluation will short-circuit and the span or event will be disabled.
417//!
418//! ### Enabling Interest
419//!
420//! Whenever an tracing event (or span) is emitted, it goes through a number of
421//! steps to determine how and how much it should be processed. The earlier an
422//! event is disabled, the less work has to be done to process the event, so
423//! `Layer`s that implement filtering should attempt to disable unwanted
424//! events as early as possible. In order, each event checks:
425//!
426//! - [`register_callsite`], once per callsite (roughly: once per time that
427//!   `event!` or `span!` is written in the source code; this is cached at the
428//!   callsite). See [`Subscriber::register_callsite`] and
429//!   [`tracing_core::callsite`] for a summary of how this behaves.
430//! - [`enabled`], once per emitted event (roughly: once per time that `event!`
431//!   or `span!` is *executed*), and only if `register_callsite` registers an
432//!   [`Interest::sometimes`]. This is the main customization point to globally
433//!   filter events based on their [`Metadata`]. If an event can be disabled
434//!   based only on [`Metadata`], it should be, as this allows the construction
435//!   of the actual `Event`/`Span` to be skipped.
436//! - For events only (and not spans), [`event_enabled`] is called just before
437//!   processing the event. This gives layers one last chance to say that
438//!   an event should be filtered out, now that the event's fields are known.
439//!
440//! ## Per-Layer Filtering
441//!
442//! **Note**: per-layer filtering APIs currently require the [`"registry"` crate
443//! feature flag][feat] to be enabled.
444//!
445//! Sometimes, it may be desirable for one `Layer` to record a particular subset
446//! of spans and events, while a different subset of spans and events are
447//! recorded by other `Layer`s. For example:
448//!
449//! - A layer that records metrics may wish to observe only events including
450//!   particular tracked values, while a logging layer ignores those events.
451//! - If recording a distributed trace is expensive, it might be desirable to
452//!   only send spans with `INFO` and lower verbosity to the distributed tracing
453//!   system, while logging more verbose spans to a file.
454//! - Spans and events with a particular target might be recorded differently
455//!   from others, such as by generating an HTTP access log from a span that
456//!   tracks the lifetime of an HTTP request.
457//!
458//! The [`Filter`] trait is used to control what spans and events are
459//! observed by an individual `Layer`, while still allowing other `Layer`s to
460//! potentially record them. The [`Layer::with_filter`] method combines a
461//! `Layer` with a [`Filter`], returning a [`Filtered`] layer.
462//!
463//! This crate's [`filter`] module provides a number of types which implement
464//! the [`Filter`] trait, such as [`LevelFilter`], [`Targets`], and
465//! [`FilterFn`]. These [`Filter`]s provide ready-made implementations of
466//! common forms of filtering. For custom filtering policies, the [`FilterFn`]
467//! and [`DynFilterFn`] types allow implementing a [`Filter`] with a closure or
468//! function pointer. In addition, when more control is required, the [`Filter`]
469//! trait may also be implemented for user-defined types.
470//!
471//! //! [`Option<Filter>`] also implements [`Filter`], which allows for an optional
472//! filter. [`None`](Option::None) filters out _nothing_ (that is, allows
473//! everything through). For example:
474//!
475//! ```rust
476//! # use tracing_subscriber::{filter::filter_fn, Layer};
477//! # use tracing_core::{Metadata, subscriber::Subscriber};
478//! # struct MyLayer<S>(std::marker::PhantomData<S>);
479//! # impl<S> MyLayer<S> { fn new() -> Self { Self(std::marker::PhantomData)} }
480//! # impl<S: Subscriber> Layer<S> for MyLayer<S> {}
481//! # fn my_filter(_: &str) -> impl Fn(&Metadata) -> bool { |_| true  }
482//! fn setup_tracing<S: Subscriber>(filter_config: Option<&str>) {
483//!     let layer = MyLayer::<S>::new()
484//!         .with_filter(filter_config.map(|config| filter_fn(my_filter(config))));
485//! //...
486//! }
487//! ```
488//!
489//! <pre class="compile_fail" style="white-space:normal;font:inherit;">
490//!     <strong>Warning</strong>: Currently, the <a href="../struct.Registry.html">
491//!     <code>Registry</code></a> type defined in this crate is the only root
492//!     <code>Subscriber</code> capable of supporting <code>Layer</code>s with
493//!     per-layer filters. In the future, new APIs will be added to allow other
494//!     root <code>Subscriber</code>s to support per-layer filters.
495//! </pre>
496//!
497//! For example, to generate an HTTP access log based on spans with
498//! the `http_access` target, while logging other spans and events to
499//! standard out, a [`Filter`] can be added to the access log layer:
500//!
501//! ```
502//! use tracing_subscriber::{filter, prelude::*};
503//!
504//! // Generates an HTTP access log.
505//! let access_log = // ...
506//!     # filter::LevelFilter::INFO;
507//!
508//! // Add a filter to the access log layer so that it only observes
509//! // spans and events with the `http_access` target.
510//! let access_log = access_log.with_filter(filter::filter_fn(|metadata| {
511//!     // Returns `true` if and only if the span or event's target is
512//!     // "http_access".
513//!     metadata.target() == "http_access"
514//! }));
515//!
516//! // A general-purpose logging layer.
517//! let fmt_layer = tracing_subscriber::fmt::layer();
518//!
519//! // Build a subscriber that combines the access log and stdout log
520//! // layers.
521//! tracing_subscriber::registry()
522//!     .with(fmt_layer)
523//!     .with(access_log)
524//!     .init();
525//! ```
526//!
527//! Multiple layers can have their own, separate per-layer filters. A span or
528//! event will be recorded if it is enabled by _any_ per-layer filter, but it
529//! will be skipped by the layers whose filters did not enable it. Building on
530//! the previous example:
531//!
532//! ```
533//! use tracing_subscriber::{filter::{filter_fn, LevelFilter}, prelude::*};
534//!
535//! let access_log = // ...
536//!     # LevelFilter::INFO;
537//! let fmt_layer = tracing_subscriber::fmt::layer();
538//!
539//! tracing_subscriber::registry()
540//!     // Add the filter for the "http_access" target to the access
541//!     // log layer, like before.
542//!     .with(access_log.with_filter(filter_fn(|metadata| {
543//!         metadata.target() == "http_access"
544//!     })))
545//!     // Add a filter for spans and events with the INFO level
546//!     // and below to the logging layer.
547//!     .with(fmt_layer.with_filter(LevelFilter::INFO))
548//!     .init();
549//!
550//! // Neither layer will observe this event
551//! tracing::debug!(does_anyone_care = false, "a tree fell in the forest");
552//!
553//! // This event will be observed by the logging layer, but not
554//! // by the access log layer.
555//! tracing::warn!(dose_roentgen = %3.8, "not great, but not terrible");
556//!
557//! // This event will be observed only by the access log layer.
558//! tracing::trace!(target: "http_access", "HTTP request started");
559//!
560//! // Both layers will observe this event.
561//! tracing::error!(target: "http_access", "HTTP request failed with a very bad error!");
562//! ```
563//!
564//! A per-layer filter can be applied to multiple [`Layer`]s at a time, by
565//! combining them into a [`Layered`] layer using [`Layer::and_then`], and then
566//! calling [`Layer::with_filter`] on the resulting [`Layered`] layer.
567//!
568//! Consider the following:
569//! - `layer_a` and `layer_b`, which should only receive spans and events at
570//!   the [`INFO`] [level] and above.
571//! - A third layer, `layer_c`, which should receive spans and events at
572//!   the [`DEBUG`] [level] as well.
573//!
574//! The layers and filters would be composed thusly:
575//!
576//! ```
577//! use tracing_subscriber::{filter::LevelFilter, prelude::*};
578//!
579//! let layer_a = // ...
580//! # LevelFilter::INFO;
581//! let layer_b =  // ...
582//! # LevelFilter::INFO;
583//! let layer_c =  // ...
584//! # LevelFilter::INFO;
585//!
586//! let info_layers = layer_a
587//!     // Combine `layer_a` and `layer_b` into a `Layered` layer:
588//!     .and_then(layer_b)
589//!     // ...and then add an `INFO` `LevelFilter` to that layer:
590//!     .with_filter(LevelFilter::INFO);
591//!
592//! tracing_subscriber::registry()
593//!     // Add `layer_c` with a `DEBUG` filter.
594//!     .with(layer_c.with_filter(LevelFilter::DEBUG))
595//!     .with(info_layers)
596//!     .init();
597//!```
598//!
599//! If a [`Filtered`] [`Layer`] is combined with another [`Layer`]
600//! [`Layer::and_then`], and a filter is added to the [`Layered`] layer, that
601//! layer will be filtered by *both* the inner filter and the outer filter.
602//! Only spans and events that are enabled by *both* filters will be
603//! observed by that layer. This can be used to implement complex filtering
604//! trees.
605//!
606//! As an example, consider the following constraints:
607//! - Suppose that a particular [target] is used to indicate events that
608//!   should be counted as part of a metrics system, which should be only
609//!   observed by a layer that collects metrics.
610//! - A log of high-priority events ([`INFO`] and above) should be logged
611//!   to stdout, while more verbose events should be logged to a debugging log file.
612//! - Metrics-focused events should *not* be included in either log output.
613//!
614//! In that case, it is possible to apply a filter to both logging layers to
615//! exclude the metrics events, while additionally adding a [`LevelFilter`]
616//! to the stdout log:
617//!
618//! ```
619//! # // wrap this in a function so we don't actually create `debug.log` when
620//! # // running the doctests..
621//! # fn docs() -> Result<(), Box<dyn std::error::Error + 'static>> {
622//! use tracing_subscriber::{filter, prelude::*};
623//! use std::{fs::File, sync::Arc};
624//!
625//! // A layer that logs events to stdout using the human-readable "pretty"
626//! // format.
627//! let stdout_log = tracing_subscriber::fmt::layer()
628//!     .pretty();
629//!
630//! // A layer that logs events to a file.
631//! let file = File::create("debug.log")?;
632//! let debug_log = tracing_subscriber::fmt::layer()
633//!     .with_writer(Arc::new(file));
634//!
635//! // A layer that collects metrics using specific events.
636//! let metrics_layer = /* ... */ filter::LevelFilter::INFO;
637//!
638//! tracing_subscriber::registry()
639//!     .with(
640//!         stdout_log
641//!             // Add an `INFO` filter to the stdout logging layer
642//!             .with_filter(filter::LevelFilter::INFO)
643//!             // Combine the filtered `stdout_log` layer with the
644//!             // `debug_log` layer, producing a new `Layered` layer.
645//!             .and_then(debug_log)
646//!             // Add a filter to *both* layers that rejects spans and
647//!             // events whose targets start with `metrics`.
648//!             .with_filter(filter::filter_fn(|metadata| {
649//!                 !metadata.target().starts_with("metrics")
650//!             }))
651//!     )
652//!     .with(
653//!         // Add a filter to the metrics label that *only* enables
654//!         // events whose targets start with `metrics`.
655//!         metrics_layer.with_filter(filter::filter_fn(|metadata| {
656//!             metadata.target().starts_with("metrics")
657//!         }))
658//!     )
659//!     .init();
660//!
661//! // This event will *only* be recorded by the metrics layer.
662//! tracing::info!(target: "metrics::cool_stuff_count", value = 42);
663//!
664//! // This event will only be seen by the debug log file layer:
665//! tracing::debug!("this is a message, and part of a system of messages");
666//!
667//! // This event will be seen by both the stdout log layer *and*
668//! // the debug log file layer, but not by the metrics layer.
669//! tracing::warn!("the message is a warning about danger!");
670//! # Ok(()) }
671//! ```
672//!
673//! [`Subscriber`]: tracing_core::subscriber::Subscriber
674//! [span IDs]: tracing_core::span::Id
675//! [the current span]: Context::current_span
676//! [`register_callsite`]: Layer::register_callsite
677//! [`enabled`]: Layer::enabled
678//! [`event_enabled`]: Layer::event_enabled
679//! [`on_enter`]: Layer::on_enter
680//! [`Layer::register_callsite`]: Layer::register_callsite
681//! [`Layer::enabled`]: Layer::enabled
682//! [`Interest::never()`]: tracing_core::subscriber::Interest::never()
683//! [`Filtered`]: crate::filter::Filtered
684//! [`filter`]: crate::filter
685//! [`Targets`]: crate::filter::Targets
686//! [`FilterFn`]: crate::filter::FilterFn
687//! [`DynFilterFn`]: crate::filter::DynFilterFn
688//! [level]: tracing_core::Level
689//! [`INFO`]: tracing_core::Level::INFO
690//! [`DEBUG`]: tracing_core::Level::DEBUG
691//! [target]: tracing_core::Metadata::target
692//! [`LevelFilter`]: crate::filter::LevelFilter
693//! [feat]: crate#feature-flags
694use crate::filter;
695
696use tracing_core::{
697    metadata::Metadata,
698    span,
699    subscriber::{Interest, Subscriber},
700    Dispatch, Event, LevelFilter,
701};
702
703use core::any::TypeId;
704
705feature! {
706    #![feature = "alloc"]
707    use alloc::boxed::Box;
708    use core::ops::{Deref, DerefMut};
709}
710
711mod context;
712mod layered;
713pub use self::{context::*, layered::*};
714
715// The `tests` module is `pub(crate)` because it contains test utilities used by
716// other modules.
717#[cfg(test)]
718pub(crate) mod tests;
719
720/// A composable handler for `tracing` events.
721///
722/// A `Layer` implements a behavior for recording or collecting traces that can
723/// be composed together with other `Layer`s to build a [`Subscriber`]. See the
724/// [module-level documentation](crate::layer) for details.
725///
726/// [`Subscriber`]: tracing_core::Subscriber
727#[cfg_attr(docsrs, doc(notable_trait))]
728pub trait Layer<S>
729where
730    S: Subscriber,
731    Self: 'static,
732{
733    /// Performs late initialization when installing this layer as a
734    /// [`Subscriber`].
735    ///
736    /// ## Avoiding Memory Leaks
737    ///
738    /// `Layer`s should not store the [`Dispatch`] pointing to the [`Subscriber`]
739    /// that they are a part of. Because the `Dispatch` owns the `Subscriber`,
740    /// storing the `Dispatch` within the `Subscriber` will create a reference
741    /// count cycle, preventing the `Dispatch` from ever being dropped.
742    ///
743    /// Instead, when it is necessary to store a cyclical reference to the
744    /// `Dispatch` within a `Layer`, use [`Dispatch::downgrade`] to convert a
745    /// `Dispatch` into a [`WeakDispatch`]. This type is analogous to
746    /// [`std::sync::Weak`], and does not create a reference count cycle. A
747    /// [`WeakDispatch`] can be stored within a subscriber without causing a
748    /// memory leak, and can be [upgraded] into a `Dispatch` temporarily when
749    /// the `Dispatch` must be accessed by the subscriber.
750    ///
751    /// [`WeakDispatch`]: tracing_core::dispatcher::WeakDispatch
752    /// [upgraded]: tracing_core::dispatcher::WeakDispatch::upgrade
753    /// [`Subscriber`]: tracing_core::Subscriber
754    fn on_register_dispatch(&self, subscriber: &Dispatch) {
755        let _ = subscriber;
756    }
757
758    /// Performs late initialization when attaching a `Layer` to a
759    /// [`Subscriber`].
760    ///
761    /// This is a callback that is called when the `Layer` is added to a
762    /// [`Subscriber`] (e.g. in [`Layer::with_subscriber`] and
763    /// [`SubscriberExt::with`]). Since this can only occur before the
764    /// [`Subscriber`] has been set as the default, both the `Layer` and
765    /// [`Subscriber`] are passed to this method _mutably_. This gives the
766    /// `Layer` the opportunity to set any of its own fields with values
767    /// received by method calls on the [`Subscriber`].
768    ///
769    /// For example, [`Filtered`] layers implement `on_layer` to call the
770    /// [`Subscriber`]'s [`register_filter`] method, and store the returned
771    /// [`FilterId`] as a field.
772    ///
773    /// **Note** In most cases, `Layer` implementations will not need to
774    /// implement this method. However, in cases where a type implementing
775    /// `Layer` wraps one or more other types that implement `Layer`, like the
776    /// [`Layered`] and [`Filtered`] types in this crate, that type MUST ensure
777    /// that the inner `Layer`s' `on_layer` methods are called. Otherwise,
778    /// functionality that relies on `on_layer`, such as [per-layer filtering],
779    /// may not work correctly.
780    ///
781    /// [`Filtered`]: crate::filter::Filtered
782    /// [`register_filter`]: crate::registry::LookupSpan::register_filter
783    /// [per-layer filtering]: #per-layer-filtering
784    /// [`FilterId`]: crate::filter::FilterId
785    fn on_layer(&mut self, subscriber: &mut S) {
786        let _ = subscriber;
787    }
788
789    /// Registers a new callsite with this layer, returning whether or not
790    /// the layer is interested in being notified about the callsite, similarly
791    /// to [`Subscriber::register_callsite`].
792    ///
793    /// By default, this returns [`Interest::always()`] if [`self.enabled`] returns
794    /// true, or [`Interest::never()`] if it returns false.
795    ///
796    /// <pre class="ignore" style="white-space:normal;font:inherit;">
797    /// <strong>Note</strong>: This method (and <a href="#method.enabled">
798    /// <code>Layer::enabled</code></a>) determine whether a span or event is
799    /// globally enabled, <em>not</em> whether the individual layer will be
800    /// notified about that span or event. This is intended to be used
801    /// by layers that implement filtering for the entire stack. Layers which do
802    /// not wish to be notified about certain spans or events but do not wish to
803    /// globally disable them should ignore those spans or events in their
804    /// <a href="#method.on_event"><code>on_event</code></a>,
805    /// <a href="#method.on_enter"><code>on_enter</code></a>,
806    /// <a href="#method.on_exit"><code>on_exit</code></a>, and other notification
807    /// methods.
808    /// </pre>
809    ///
810    /// See [the trait-level documentation] for more information on filtering
811    /// with `Layer`s.
812    ///
813    /// Layers may also implement this method to perform any behaviour that
814    /// should be run once per callsite. If the layer wishes to use
815    /// `register_callsite` for per-callsite behaviour, but does not want to
816    /// globally enable or disable those callsites, it should always return
817    /// [`Interest::always()`].
818    ///
819    /// [`Interest`]: tracing_core::Interest
820    /// [`Subscriber::register_callsite`]: tracing_core::Subscriber::register_callsite()
821    /// [`Interest::never()`]: tracing_core::subscriber::Interest::never()
822    /// [`Interest::always()`]: tracing_core::subscriber::Interest::always()
823    /// [`self.enabled`]: Layer::enabled()
824    /// [`Layer::enabled`]: Layer::enabled()
825    /// [`on_event`]: Layer::on_event()
826    /// [`on_enter`]: Layer::on_enter()
827    /// [`on_exit`]: Layer::on_exit()
828    /// [the trait-level documentation]: #filtering-with-layers
829    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
830        if self.enabled(metadata, Context::none()) {
831            Interest::always()
832        } else {
833            Interest::never()
834        }
835    }
836
837    /// Returns `true` if this layer is interested in a span or event with the
838    /// given `metadata` in the current [`Context`], similarly to
839    /// [`Subscriber::enabled`].
840    ///
841    /// By default, this always returns `true`, allowing the wrapped subscriber
842    /// to choose to disable the span.
843    ///
844    /// <pre class="ignore" style="white-space:normal;font:inherit;">
845    /// <strong>Note</strong>: This method (and <a href="#method.register_callsite">
846    /// <code>Layer::register_callsite</code></a>) determine whether a span or event is
847    /// globally enabled, <em>not</em> whether the individual layer will be
848    /// notified about that span or event. This is intended to be used
849    /// by layers that implement filtering for the entire stack. Layers which do
850    /// not wish to be notified about certain spans or events but do not wish to
851    /// globally disable them should ignore those spans or events in their
852    /// <a href="#method.on_event"><code>on_event</code></a>,
853    /// <a href="#method.on_enter"><code>on_enter</code></a>,
854    /// <a href="#method.on_exit"><code>on_exit</code></a>, and other notification
855    /// methods.
856    /// </pre>
857    ///
858    ///
859    /// See [the trait-level documentation] for more information on filtering
860    /// with `Layer`s.
861    ///
862    /// [`Interest`]: tracing_core::Interest
863    /// [`Subscriber::enabled`]: tracing_core::Subscriber::enabled()
864    /// [`Layer::register_callsite`]: Layer::register_callsite()
865    /// [`on_event`]: Layer::on_event()
866    /// [`on_enter`]: Layer::on_enter()
867    /// [`on_exit`]: Layer::on_exit()
868    /// [the trait-level documentation]: #filtering-with-layers
869    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
870        let _ = (metadata, ctx);
871        true
872    }
873
874    /// Notifies this layer that a new span was constructed with the given
875    /// `Attributes` and `Id`.
876    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
877        let _ = (attrs, id, ctx);
878    }
879
880    // TODO(eliza): do we want this to be a public API? If we end up moving
881    // filtering layers to a separate trait, we may no longer want `Layer`s to
882    // be able to participate in max level hinting...
883    #[doc(hidden)]
884    fn max_level_hint(&self) -> Option<LevelFilter> {
885        None
886    }
887
888    /// Notifies this layer that a span with the given `Id` recorded the given
889    /// `values`.
890    // Note: it's unclear to me why we'd need the current span in `record` (the
891    // only thing the `Context` type currently provides), but passing it in anyway
892    // seems like a good future-proofing measure as it may grow other methods later...
893    fn on_record(&self, _span: &span::Id, _values: &span::Record<'_>, _ctx: Context<'_, S>) {}
894
895    /// Notifies this layer that a span with the ID `span` recorded that it
896    /// follows from the span with the ID `follows`.
897    // Note: it's unclear to me why we'd need the current span in `record` (the
898    // only thing the `Context` type currently provides), but passing it in anyway
899    // seems like a good future-proofing measure as it may grow other methods later...
900    fn on_follows_from(&self, _span: &span::Id, _follows: &span::Id, _ctx: Context<'_, S>) {}
901
902    /// Called before [`on_event`], to determine if `on_event` should be called.
903    ///
904    /// <div class="example-wrap" style="display:inline-block">
905    /// <pre class="ignore" style="white-space:normal;font:inherit;">
906    ///
907    /// **Note**: This method determines whether an event is globally enabled,
908    /// *not* whether the individual `Layer` will be notified about the
909    /// event. This is intended to be used by `Layer`s that implement
910    /// filtering for the entire stack. `Layer`s which do not wish to be
911    /// notified about certain events but do not wish to globally disable them
912    /// should ignore those events in their [on_event][Self::on_event].
913    ///
914    /// </pre></div>
915    ///
916    /// See [the trait-level documentation] for more information on filtering
917    /// with `Layer`s.
918    ///
919    /// [`on_event`]: Self::on_event
920    /// [`Interest`]: tracing_core::Interest
921    /// [the trait-level documentation]: #filtering-with-layers
922    #[inline] // collapse this to a constant please mrs optimizer
923    fn event_enabled(&self, _event: &Event<'_>, _ctx: Context<'_, S>) -> bool {
924        true
925    }
926
927    /// Notifies this layer that an event has occurred.
928    fn on_event(&self, _event: &Event<'_>, _ctx: Context<'_, S>) {}
929
930    /// Notifies this layer that a span with the given ID was entered.
931    fn on_enter(&self, _id: &span::Id, _ctx: Context<'_, S>) {}
932
933    /// Notifies this layer that the span with the given ID was exited.
934    fn on_exit(&self, _id: &span::Id, _ctx: Context<'_, S>) {}
935
936    /// Notifies this layer that the span with the given ID has been closed.
937    fn on_close(&self, _id: span::Id, _ctx: Context<'_, S>) {}
938
939    /// Notifies this layer that a span ID has been cloned, and that the
940    /// subscriber returned a different ID.
941    fn on_id_change(&self, _old: &span::Id, _new: &span::Id, _ctx: Context<'_, S>) {}
942
943    /// Composes this layer around the given `Layer`, returning a `Layered`
944    /// struct implementing `Layer`.
945    ///
946    /// The returned `Layer` will call the methods on this `Layer` and then
947    /// those of the new `Layer`, before calling the methods on the subscriber
948    /// it wraps. For example:
949    ///
950    /// ```rust
951    /// # use tracing_subscriber::layer::Layer;
952    /// # use tracing_core::Subscriber;
953    /// pub struct FooLayer {
954    ///     // ...
955    /// }
956    ///
957    /// pub struct BarLayer {
958    ///     // ...
959    /// }
960    ///
961    /// pub struct MySubscriber {
962    ///     // ...
963    /// }
964    ///
965    /// impl<S: Subscriber> Layer<S> for FooLayer {
966    ///     // ...
967    /// }
968    ///
969    /// impl<S: Subscriber> Layer<S> for BarLayer {
970    ///     // ...
971    /// }
972    ///
973    /// # impl FooLayer {
974    /// # fn new() -> Self { Self {} }
975    /// # }
976    /// # impl BarLayer {
977    /// # fn new() -> Self { Self { }}
978    /// # }
979    /// # impl MySubscriber {
980    /// # fn new() -> Self { Self { }}
981    /// # }
982    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
983    /// # impl tracing_core::Subscriber for MySubscriber {
984    /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
985    /// #   fn record(&self, _: &Id, _: &Record) {}
986    /// #   fn event(&self, _: &Event) {}
987    /// #   fn record_follows_from(&self, _: &Id, _: &Id) {}
988    /// #   fn enabled(&self, _: &Metadata) -> bool { false }
989    /// #   fn enter(&self, _: &Id) {}
990    /// #   fn exit(&self, _: &Id) {}
991    /// # }
992    /// let subscriber = FooLayer::new()
993    ///     .and_then(BarLayer::new())
994    ///     .with_subscriber(MySubscriber::new());
995    /// ```
996    ///
997    /// Multiple layers may be composed in this manner:
998    ///
999    /// ```rust
1000    /// # use tracing_subscriber::layer::Layer;
1001    /// # use tracing_core::Subscriber;
1002    /// # pub struct FooLayer {}
1003    /// # pub struct BarLayer {}
1004    /// # pub struct MySubscriber {}
1005    /// # impl<S: Subscriber> Layer<S> for FooLayer {}
1006    /// # impl<S: Subscriber> Layer<S> for BarLayer {}
1007    /// # impl FooLayer {
1008    /// # fn new() -> Self { Self {} }
1009    /// # }
1010    /// # impl BarLayer {
1011    /// # fn new() -> Self { Self { }}
1012    /// # }
1013    /// # impl MySubscriber {
1014    /// # fn new() -> Self { Self { }}
1015    /// # }
1016    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
1017    /// # impl tracing_core::Subscriber for MySubscriber {
1018    /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
1019    /// #   fn record(&self, _: &Id, _: &Record) {}
1020    /// #   fn event(&self, _: &Event) {}
1021    /// #   fn record_follows_from(&self, _: &Id, _: &Id) {}
1022    /// #   fn enabled(&self, _: &Metadata) -> bool { false }
1023    /// #   fn enter(&self, _: &Id) {}
1024    /// #   fn exit(&self, _: &Id) {}
1025    /// # }
1026    /// pub struct BazLayer {
1027    ///     // ...
1028    /// }
1029    ///
1030    /// impl<S: Subscriber> Layer<S> for BazLayer {
1031    ///     // ...
1032    /// }
1033    /// # impl BazLayer { fn new() -> Self { BazLayer {} } }
1034    ///
1035    /// let subscriber = FooLayer::new()
1036    ///     .and_then(BarLayer::new())
1037    ///     .and_then(BazLayer::new())
1038    ///     .with_subscriber(MySubscriber::new());
1039    /// ```
1040    fn and_then<L>(self, layer: L) -> Layered<L, Self, S>
1041    where
1042        L: Layer<S>,
1043        Self: Sized,
1044    {
1045        let inner_has_layer_filter = filter::layer_has_plf(&self);
1046        Layered::new(layer, self, inner_has_layer_filter)
1047    }
1048
1049    /// Composes this `Layer` with the given [`Subscriber`], returning a
1050    /// `Layered` struct that implements [`Subscriber`].
1051    ///
1052    /// The returned `Layered` subscriber will call the methods on this `Layer`
1053    /// and then those of the wrapped subscriber.
1054    ///
1055    /// For example:
1056    /// ```rust
1057    /// # use tracing_subscriber::layer::Layer;
1058    /// # use tracing_core::Subscriber;
1059    /// pub struct FooLayer {
1060    ///     // ...
1061    /// }
1062    ///
1063    /// pub struct MySubscriber {
1064    ///     // ...
1065    /// }
1066    ///
1067    /// impl<S: Subscriber> Layer<S> for FooLayer {
1068    ///     // ...
1069    /// }
1070    ///
1071    /// # impl FooLayer {
1072    /// # fn new() -> Self { Self {} }
1073    /// # }
1074    /// # impl MySubscriber {
1075    /// # fn new() -> Self { Self { }}
1076    /// # }
1077    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata};
1078    /// # impl tracing_core::Subscriber for MySubscriber {
1079    /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
1080    /// #   fn record(&self, _: &Id, _: &Record) {}
1081    /// #   fn event(&self, _: &tracing_core::Event) {}
1082    /// #   fn record_follows_from(&self, _: &Id, _: &Id) {}
1083    /// #   fn enabled(&self, _: &Metadata) -> bool { false }
1084    /// #   fn enter(&self, _: &Id) {}
1085    /// #   fn exit(&self, _: &Id) {}
1086    /// # }
1087    /// let subscriber = FooLayer::new()
1088    ///     .with_subscriber(MySubscriber::new());
1089    ///```
1090    ///
1091    /// [`Subscriber`]: tracing_core::Subscriber
1092    fn with_subscriber(mut self, mut inner: S) -> Layered<Self, S>
1093    where
1094        Self: Sized,
1095    {
1096        let inner_has_layer_filter = filter::subscriber_has_plf(&inner);
1097        self.on_layer(&mut inner);
1098        Layered::new(self, inner, inner_has_layer_filter)
1099    }
1100
1101    /// Combines `self` with a [`Filter`], returning a [`Filtered`] layer.
1102    ///
1103    /// The [`Filter`] will control which spans and events are enabled for
1104    /// this layer. See [the trait-level documentation][plf] for details on
1105    /// per-layer filtering.
1106    ///
1107    /// [`Filtered`]: crate::filter::Filtered
1108    /// [plf]: crate::layer#per-layer-filtering
1109    #[cfg(all(feature = "registry", feature = "std"))]
1110    #[cfg_attr(docsrs, doc(cfg(all(feature = "registry", feature = "std"))))]
1111    fn with_filter<F>(self, filter: F) -> filter::Filtered<Self, F, S>
1112    where
1113        Self: Sized,
1114        F: Filter<S>,
1115    {
1116        filter::Filtered::new(self, filter)
1117    }
1118
1119    /// Erases the type of this [`Layer`], returning a [`Box`]ed `dyn
1120    /// Layer` trait object.
1121    ///
1122    /// This can be used when a function returns a `Layer` which may be of
1123    /// one of several types, or when a `Layer` subscriber has a very long type
1124    /// signature.
1125    ///
1126    /// # Examples
1127    ///
1128    /// The following example will *not* compile, because the value assigned to
1129    /// `log_layer` may have one of several different types:
1130    ///
1131    /// ```compile_fail
1132    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1133    /// use tracing_subscriber::{Layer, filter::LevelFilter, prelude::*};
1134    /// use std::{path::PathBuf, fs::File, io};
1135    ///
1136    /// /// Configures whether logs are emitted to a file, to stdout, or to stderr.
1137    /// pub enum LogConfig {
1138    ///     File(PathBuf),
1139    ///     Stdout,
1140    ///     Stderr,
1141    /// }
1142    ///
1143    /// let config = // ...
1144    ///     # LogConfig::Stdout;
1145    ///
1146    /// // Depending on the config, construct a layer of one of several types.
1147    /// let log_layer = match config {
1148    ///     // If logging to a file, use a maximally-verbose configuration.
1149    ///     LogConfig::File(path) => {
1150    ///         let file = File::create(path)?;
1151    ///         tracing_subscriber::fmt::layer()
1152    ///             .with_thread_ids(true)
1153    ///             .with_thread_names(true)
1154    ///             // Selecting the JSON logging format changes the layer's
1155    ///             // type.
1156    ///             .json()
1157    ///             .with_span_list(true)
1158    ///             // Setting the writer to use our log file changes the
1159    ///             // layer's type again.
1160    ///             .with_writer(file)
1161    ///     },
1162    ///
1163    ///     // If logging to stdout, use a pretty, human-readable configuration.
1164    ///     LogConfig::Stdout => tracing_subscriber::fmt::layer()
1165    ///         // Selecting the "pretty" logging format changes the
1166    ///         // layer's type!
1167    ///         .pretty()
1168    ///         .with_writer(io::stdout)
1169    ///         // Add a filter based on the RUST_LOG environment variable;
1170    ///         // this changes the type too!
1171    ///         .and_then(tracing_subscriber::EnvFilter::from_default_env()),
1172    ///
1173    ///     // If logging to stdout, only log errors and warnings.
1174    ///     LogConfig::Stderr => tracing_subscriber::fmt::layer()
1175    ///         // Changing the writer changes the layer's type
1176    ///         .with_writer(io::stderr)
1177    ///         // Only log the `WARN` and `ERROR` levels. Adding a filter
1178    ///         // changes the layer's type to `Filtered<LevelFilter, ...>`.
1179    ///         .with_filter(LevelFilter::WARN),
1180    /// };
1181    ///
1182    /// tracing_subscriber::registry()
1183    ///     .with(log_layer)
1184    ///     .init();
1185    /// # Ok(()) }
1186    /// ```
1187    ///
1188    /// However, adding a call to `.boxed()` after each match arm erases the
1189    /// layer's type, so this code *does* compile:
1190    ///
1191    /// ```
1192    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1193    /// # use tracing_subscriber::{Layer, filter::LevelFilter, prelude::*};
1194    /// # use std::{path::PathBuf, fs::File, io};
1195    /// # pub enum LogConfig {
1196    /// #    File(PathBuf),
1197    /// #    Stdout,
1198    /// #    Stderr,
1199    /// # }
1200    /// # let config = LogConfig::Stdout;
1201    /// let log_layer = match config {
1202    ///     LogConfig::File(path) => {
1203    ///         let file = File::create(path)?;
1204    ///         tracing_subscriber::fmt::layer()
1205    ///             .with_thread_ids(true)
1206    ///             .with_thread_names(true)
1207    ///             .json()
1208    ///             .with_span_list(true)
1209    ///             .with_writer(file)
1210    ///             // Erase the type by boxing the layer
1211    ///             .boxed()
1212    ///     },
1213    ///
1214    ///     LogConfig::Stdout => tracing_subscriber::fmt::layer()
1215    ///         .pretty()
1216    ///         .with_writer(io::stdout)
1217    ///         .and_then(tracing_subscriber::EnvFilter::from_default_env())
1218    ///         // Erase the type by boxing the layer
1219    ///         .boxed(),
1220    ///
1221    ///     LogConfig::Stderr => tracing_subscriber::fmt::layer()
1222    ///         .with_writer(io::stderr)
1223    ///         .with_filter(LevelFilter::WARN)
1224    ///         // Erase the type by boxing the layer
1225    ///         .boxed(),
1226    /// };
1227    ///
1228    /// tracing_subscriber::registry()
1229    ///     .with(log_layer)
1230    ///     .init();
1231    /// # Ok(()) }
1232    /// ```
1233    #[cfg(any(feature = "alloc", feature = "std"))]
1234    #[cfg_attr(docsrs, doc(cfg(any(feature = "alloc", feature = "std"))))]
1235    fn boxed(self) -> Box<dyn Layer<S> + Send + Sync + 'static>
1236    where
1237        Self: Sized,
1238        Self: Layer<S> + Send + Sync + 'static,
1239        S: Subscriber,
1240    {
1241        Box::new(self)
1242    }
1243
1244    #[doc(hidden)]
1245    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1246        if id == TypeId::of::<Self>() {
1247            Some(self as *const _ as *const ())
1248        } else {
1249            None
1250        }
1251    }
1252}
1253
1254feature! {
1255    #![all(feature = "registry", feature = "std")]
1256
1257    /// A per-[`Layer`] filter that determines whether a span or event is enabled
1258    /// for an individual layer.
1259    ///
1260    /// See [the module-level documentation][plf] for details on using [`Filter`]s.
1261    ///
1262    /// [plf]: crate::layer#per-layer-filtering
1263    #[cfg_attr(docsrs, doc(notable_trait))]
1264    pub trait Filter<S> {
1265        /// Returns `true` if this layer is interested in a span or event with the
1266        /// given [`Metadata`] in the current [`Context`], similarly to
1267        /// [`Subscriber::enabled`].
1268        ///
1269        /// If this returns `false`, the span or event will be disabled _for the
1270        /// wrapped [`Layer`]_. Unlike [`Layer::enabled`], the span or event will
1271        /// still be recorded if any _other_ layers choose to enable it. However,
1272        /// the layer [filtered] by this filter will skip recording that span or
1273        /// event.
1274        ///
1275        /// If all layers indicate that they do not wish to see this span or event,
1276        /// it will be disabled.
1277        ///
1278        /// [`metadata`]: tracing_core::Metadata
1279        /// [`Subscriber::enabled`]: tracing_core::Subscriber::enabled
1280        /// [filtered]: crate::filter::Filtered
1281        fn enabled(&self, meta: &Metadata<'_>, cx: &Context<'_, S>) -> bool;
1282
1283        /// Returns an [`Interest`] indicating whether this layer will [always],
1284        /// [sometimes], or [never] be interested in the given [`Metadata`].
1285        ///
1286        /// When a given callsite will [always] or [never] be enabled, the results
1287        /// of evaluating the filter may be cached for improved performance.
1288        /// Therefore, if a filter is capable of determining that it will always or
1289        /// never enable a particular callsite, providing an implementation of this
1290        /// function is recommended.
1291        ///
1292        /// <pre class="ignore" style="white-space:normal;font:inherit;">
1293        /// <strong>Note</strong>: If a <code>Filter</code> will perform
1294        /// <em>dynamic filtering</em> that depends on the current context in which
1295        /// a span or event was observed (e.g. only enabling an event when it
1296        /// occurs within a particular span), it <strong>must</strong> return
1297        /// <code>Interest::sometimes()</code> from this method. If it returns
1298        /// <code>Interest::always()</code> or <code>Interest::never()</code>, the
1299        /// <code>enabled</code> method may not be called when a particular instance
1300        /// of that span or event is recorded.
1301        /// </pre>
1302        ///
1303        /// This method is broadly similar to [`Subscriber::register_callsite`];
1304        /// however, since the returned value represents only the interest of
1305        /// *this* layer, the resulting behavior is somewhat different.
1306        ///
1307        /// If a [`Subscriber`] returns [`Interest::always()`][always] or
1308        /// [`Interest::never()`][never] for a given [`Metadata`], its [`enabled`]
1309        /// method is then *guaranteed* to never be called for that callsite. On the
1310        /// other hand, when a `Filter` returns [`Interest::always()`][always] or
1311        /// [`Interest::never()`][never] for a callsite, _other_ [`Layer`]s may have
1312        /// differing interests in that callsite. If this is the case, the callsite
1313        /// will receive [`Interest::sometimes()`][sometimes], and the [`enabled`]
1314        /// method will still be called for that callsite when it records a span or
1315        /// event.
1316        ///
1317        /// Returning [`Interest::always()`][always] or [`Interest::never()`][never] from
1318        /// `Filter::callsite_enabled` will permanently enable or disable a
1319        /// callsite (without requiring subsequent calls to [`enabled`]) if and only
1320        /// if the following is true:
1321        ///
1322        /// - all [`Layer`]s that comprise the subscriber include `Filter`s
1323        ///   (this includes a tree of [`Layered`] layers that share the same
1324        ///   `Filter`)
1325        /// - all those `Filter`s return the same [`Interest`].
1326        ///
1327        /// For example, if a [`Subscriber`] consists of two [`Filtered`] layers,
1328        /// and both of those layers return [`Interest::never()`][never], that
1329        /// callsite *will* never be enabled, and the [`enabled`] methods of those
1330        /// [`Filter`]s will not be called.
1331        ///
1332        /// ## Default Implementation
1333        ///
1334        /// The default implementation of this method assumes that the
1335        /// `Filter`'s [`enabled`] method _may_ perform dynamic filtering, and
1336        /// returns [`Interest::sometimes()`][sometimes], to ensure that [`enabled`]
1337        /// is called to determine whether a particular _instance_ of the callsite
1338        /// is enabled in the current context. If this is *not* the case, and the
1339        /// `Filter`'s [`enabled`] method will always return the same result
1340        /// for a particular [`Metadata`], this method can be overridden as
1341        /// follows:
1342        ///
1343        /// ```
1344        /// use tracing_subscriber::layer;
1345        /// use tracing_core::{Metadata, subscriber::Interest};
1346        ///
1347        /// struct MyFilter {
1348        ///     // ...
1349        /// }
1350        ///
1351        /// impl MyFilter {
1352        ///     // The actual logic for determining whether a `Metadata` is enabled
1353        ///     // must be factored out from the `enabled` method, so that it can be
1354        ///     // called without a `Context` (which is not provided to the
1355        ///     // `callsite_enabled` method).
1356        ///     fn is_enabled(&self, metadata: &Metadata<'_>) -> bool {
1357        ///         // ...
1358        ///         # drop(metadata); true
1359        ///     }
1360        /// }
1361        ///
1362        /// impl<S> layer::Filter<S> for MyFilter {
1363        ///     fn enabled(&self, metadata: &Metadata<'_>, _: &layer::Context<'_, S>) -> bool {
1364        ///         // Even though we are implementing `callsite_enabled`, we must still provide a
1365        ///         // working implementation of `enabled`, as returning `Interest::always()` or
1366        ///         // `Interest::never()` will *allow* caching, but will not *guarantee* it.
1367        ///         // Other filters may still return `Interest::sometimes()`, so we may be
1368        ///         // asked again in `enabled`.
1369        ///         self.is_enabled(metadata)
1370        ///     }
1371        ///
1372        ///     fn callsite_enabled(&self, metadata: &'static Metadata<'static>) -> Interest {
1373        ///         // The result of `self.enabled(metadata, ...)` will always be
1374        ///         // the same for any given `Metadata`, so we can convert it into
1375        ///         // an `Interest`:
1376        ///         if self.is_enabled(metadata) {
1377        ///             Interest::always()
1378        ///         } else {
1379        ///             Interest::never()
1380        ///         }
1381        ///     }
1382        /// }
1383        /// ```
1384        ///
1385        /// [`Metadata`]: tracing_core::Metadata
1386        /// [`Interest`]: tracing_core::Interest
1387        /// [always]: tracing_core::Interest::always
1388        /// [sometimes]: tracing_core::Interest::sometimes
1389        /// [never]: tracing_core::Interest::never
1390        /// [`Subscriber::register_callsite`]: tracing_core::Subscriber::register_callsite
1391        /// [`Subscriber`]: tracing_core::Subscriber
1392        /// [`enabled`]: Filter::enabled
1393        /// [`Filtered`]: crate::filter::Filtered
1394        fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
1395            let _ = meta;
1396            Interest::sometimes()
1397        }
1398
1399        /// Called before the filtered [`Layer]'s [`on_event`], to determine if
1400        /// `on_event` should be called.
1401        ///
1402        /// This gives a chance to filter events based on their fields. Note,
1403        /// however, that this *does not* override [`enabled`], and is not even
1404        /// called if [`enabled`] returns `false`.
1405        ///
1406        /// ## Default Implementation
1407        ///
1408        /// By default, this method returns `true`, indicating that no events are
1409        /// filtered out based on their fields.
1410        ///
1411        /// [`enabled`]: crate::layer::Filter::enabled
1412        /// [`on_event`]: crate::layer::Layer::on_event
1413        #[inline] // collapse this to a constant please mrs optimizer
1414        fn event_enabled(&self, event: &Event<'_>, cx: &Context<'_, S>) -> bool {
1415            let _ = (event, cx);
1416            true
1417        }
1418
1419        /// Returns an optional hint of the highest [verbosity level][level] that
1420        /// this `Filter` will enable.
1421        ///
1422        /// If this method returns a [`LevelFilter`], it will be used as a hint to
1423        /// determine the most verbose level that will be enabled. This will allow
1424        /// spans and events which are more verbose than that level to be skipped
1425        /// more efficiently. An implementation of this method is optional, but
1426        /// strongly encouraged.
1427        ///
1428        /// If the maximum level the `Filter` will enable can change over the
1429        /// course of its lifetime, it is free to return a different value from
1430        /// multiple invocations of this method. However, note that changes in the
1431        /// maximum level will **only** be reflected after the callsite [`Interest`]
1432        /// cache is rebuilt, by calling the
1433        /// [`tracing_core::callsite::rebuild_interest_cache`][rebuild] function.
1434        /// Therefore, if the `Filter will change the value returned by this
1435        /// method, it is responsible for ensuring that
1436        /// [`rebuild_interest_cache`][rebuild] is called after the value of the max
1437        /// level changes.
1438        ///
1439        /// ## Default Implementation
1440        ///
1441        /// By default, this method returns `None`, indicating that the maximum
1442        /// level is unknown.
1443        ///
1444        /// [level]: tracing_core::metadata::Level
1445        /// [`LevelFilter`]: crate::filter::LevelFilter
1446        /// [`Interest`]: tracing_core::subscriber::Interest
1447        /// [rebuild]: tracing_core::callsite::rebuild_interest_cache
1448        fn max_level_hint(&self) -> Option<LevelFilter> {
1449            None
1450        }
1451
1452        /// Notifies this filter that a new span was constructed with the given
1453        /// `Attributes` and `Id`.
1454        ///
1455        /// By default, this method does nothing. `Filter` implementations that
1456        /// need to be notified when new spans are created can override this
1457        /// method.
1458        fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1459            let _ = (attrs, id, ctx);
1460        }
1461
1462
1463        /// Notifies this filter that a span with the given `Id` recorded the given
1464        /// `values`.
1465        ///
1466        /// By default, this method does nothing. `Filter` implementations that
1467        /// need to be notified when new spans are created can override this
1468        /// method.
1469        fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1470            let _ = (id, values, ctx);
1471        }
1472
1473        /// Notifies this filter that a span with the given ID was entered.
1474        ///
1475        /// By default, this method does nothing. `Filter` implementations that
1476        /// need to be notified when a span is entered can override this method.
1477        fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1478            let _ = (id, ctx);
1479        }
1480
1481        /// Notifies this filter that a span with the given ID was exited.
1482        ///
1483        /// By default, this method does nothing. `Filter` implementations that
1484        /// need to be notified when a span is exited can override this method.
1485        fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1486            let _ = (id, ctx);
1487        }
1488
1489        /// Notifies this filter that a span with the given ID has been closed.
1490        ///
1491        /// By default, this method does nothing. `Filter` implementations that
1492        /// need to be notified when a span is closed can override this method.
1493        fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1494            let _ = (id, ctx);
1495        }
1496    }
1497}
1498
1499/// Extension trait adding a `with(Layer)` combinator to `Subscriber`s.
1500pub trait SubscriberExt: Subscriber + crate::sealed::Sealed {
1501    /// Wraps `self` with the provided `layer`.
1502    fn with<L>(self, layer: L) -> Layered<L, Self>
1503    where
1504        L: Layer<Self>,
1505        Self: Sized,
1506    {
1507        layer.with_subscriber(self)
1508    }
1509}
1510
1511/// A layer that does nothing.
1512#[derive(Clone, Debug, Default)]
1513pub struct Identity {
1514    _p: (),
1515}
1516
1517// === impl Layer ===
1518
1519#[derive(Clone, Copy)]
1520pub(crate) struct NoneLayerMarker(());
1521static NONE_LAYER_MARKER: NoneLayerMarker = NoneLayerMarker(());
1522
1523/// Is a type implementing `Layer` `Option::<_>::None`?
1524pub(crate) fn layer_is_none<L, S>(layer: &L) -> bool
1525where
1526    L: Layer<S>,
1527    S: Subscriber,
1528{
1529    unsafe {
1530        // Safety: we're not actually *doing* anything with this pointer ---
1531        // this only care about the `Option`, which is essentially being used
1532        // as a bool. We can rely on the pointer being valid, because it is
1533        // a crate-private type, and is only returned by the `Layer` impl
1534        // for `Option`s. However, even if the layer *does* decide to be
1535        // evil and give us an invalid pointer here, that's fine, because we'll
1536        // never actually dereference it.
1537        layer.downcast_raw(TypeId::of::<NoneLayerMarker>())
1538    }
1539    .is_some()
1540}
1541
1542/// Is a type implementing `Subscriber` `Option::<_>::None`?
1543pub(crate) fn subscriber_is_none<S>(subscriber: &S) -> bool
1544where
1545    S: Subscriber,
1546{
1547    unsafe {
1548        // Safety: we're not actually *doing* anything with this pointer ---
1549        // this only care about the `Option`, which is essentially being used
1550        // as a bool. We can rely on the pointer being valid, because it is
1551        // a crate-private type, and is only returned by the `Layer` impl
1552        // for `Option`s. However, even if the subscriber *does* decide to be
1553        // evil and give us an invalid pointer here, that's fine, because we'll
1554        // never actually dereference it.
1555        subscriber.downcast_raw(TypeId::of::<NoneLayerMarker>())
1556    }
1557    .is_some()
1558}
1559
1560impl<L, S> Layer<S> for Option<L>
1561where
1562    L: Layer<S>,
1563    S: Subscriber,
1564{
1565    fn on_layer(&mut self, subscriber: &mut S) {
1566        if let Some(ref mut layer) = self {
1567            layer.on_layer(subscriber)
1568        }
1569    }
1570
1571    #[inline]
1572    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1573        if let Some(ref inner) = self {
1574            inner.on_new_span(attrs, id, ctx)
1575        }
1576    }
1577
1578    #[inline]
1579    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
1580        match self {
1581            Some(ref inner) => inner.register_callsite(metadata),
1582            None => Interest::always(),
1583        }
1584    }
1585
1586    #[inline]
1587    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
1588        match self {
1589            Some(ref inner) => inner.enabled(metadata, ctx),
1590            None => true,
1591        }
1592    }
1593
1594    #[inline]
1595    fn max_level_hint(&self) -> Option<LevelFilter> {
1596        match self {
1597            Some(ref inner) => inner.max_level_hint(),
1598            None => {
1599                // There is no inner layer, so this layer will
1600                // never enable anything.
1601                Some(LevelFilter::OFF)
1602            }
1603        }
1604    }
1605
1606    #[inline]
1607    fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1608        if let Some(ref inner) = self {
1609            inner.on_record(span, values, ctx);
1610        }
1611    }
1612
1613    #[inline]
1614    fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
1615        if let Some(ref inner) = self {
1616            inner.on_follows_from(span, follows, ctx);
1617        }
1618    }
1619
1620    #[inline]
1621    fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
1622        match self {
1623            Some(ref inner) => inner.event_enabled(event, ctx),
1624            None => true,
1625        }
1626    }
1627
1628    #[inline]
1629    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
1630        if let Some(ref inner) = self {
1631            inner.on_event(event, ctx);
1632        }
1633    }
1634
1635    #[inline]
1636    fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1637        if let Some(ref inner) = self {
1638            inner.on_enter(id, ctx);
1639        }
1640    }
1641
1642    #[inline]
1643    fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1644        if let Some(ref inner) = self {
1645            inner.on_exit(id, ctx);
1646        }
1647    }
1648
1649    #[inline]
1650    fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1651        if let Some(ref inner) = self {
1652            inner.on_close(id, ctx);
1653        }
1654    }
1655
1656    #[inline]
1657    fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
1658        if let Some(ref inner) = self {
1659            inner.on_id_change(old, new, ctx)
1660        }
1661    }
1662
1663    #[doc(hidden)]
1664    #[inline]
1665    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1666        if id == TypeId::of::<Self>() {
1667            Some(self as *const _ as *const ())
1668        } else if id == TypeId::of::<NoneLayerMarker>() && self.is_none() {
1669            Some(&NONE_LAYER_MARKER as *const _ as *const ())
1670        } else {
1671            self.as_ref().and_then(|inner| inner.downcast_raw(id))
1672        }
1673    }
1674}
1675
1676feature! {
1677    #![any(feature = "std", feature = "alloc")]
1678    #[cfg(not(feature = "std"))]
1679    use alloc::vec::Vec;
1680
1681    macro_rules! layer_impl_body {
1682        () => {
1683            #[inline]
1684            fn on_register_dispatch(&self, subscriber: &Dispatch) {
1685                self.deref().on_register_dispatch(subscriber);
1686            }
1687
1688            #[inline]
1689            fn on_layer(&mut self, subscriber: &mut S) {
1690                self.deref_mut().on_layer(subscriber);
1691            }
1692
1693            #[inline]
1694            fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1695                self.deref().on_new_span(attrs, id, ctx)
1696            }
1697
1698            #[inline]
1699            fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
1700                self.deref().register_callsite(metadata)
1701            }
1702
1703            #[inline]
1704            fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
1705                self.deref().enabled(metadata, ctx)
1706            }
1707
1708            #[inline]
1709            fn max_level_hint(&self) -> Option<LevelFilter> {
1710                self.deref().max_level_hint()
1711            }
1712
1713            #[inline]
1714            fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1715                self.deref().on_record(span, values, ctx)
1716            }
1717
1718            #[inline]
1719            fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
1720                self.deref().on_follows_from(span, follows, ctx)
1721            }
1722
1723            #[inline]
1724            fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
1725                self.deref().event_enabled(event, ctx)
1726            }
1727
1728            #[inline]
1729            fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
1730                self.deref().on_event(event, ctx)
1731            }
1732
1733            #[inline]
1734            fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1735                self.deref().on_enter(id, ctx)
1736            }
1737
1738            #[inline]
1739            fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1740                self.deref().on_exit(id, ctx)
1741            }
1742
1743            #[inline]
1744            fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1745                self.deref().on_close(id, ctx)
1746            }
1747
1748            #[inline]
1749            fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
1750                self.deref().on_id_change(old, new, ctx)
1751            }
1752
1753            #[doc(hidden)]
1754            #[inline]
1755            unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1756                self.deref().downcast_raw(id)
1757            }
1758        };
1759    }
1760
1761    impl<L, S> Layer<S> for Box<L>
1762    where
1763        L: Layer<S>,
1764        S: Subscriber,
1765    {
1766        layer_impl_body! {}
1767    }
1768
1769    impl<S> Layer<S> for Box<dyn Layer<S> + Send + Sync>
1770    where
1771        S: Subscriber,
1772    {
1773        layer_impl_body! {}
1774    }
1775
1776
1777
1778    impl<S, L> Layer<S> for Vec<L>
1779    where
1780        L: Layer<S>,
1781        S: Subscriber,
1782    {
1783
1784        fn on_layer(&mut self, subscriber: &mut S) {
1785            for l in self {
1786                l.on_layer(subscriber);
1787            }
1788        }
1789
1790        fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
1791            // Return highest level of interest.
1792            let mut interest = Interest::never();
1793            for l in self {
1794                let new_interest = l.register_callsite(metadata);
1795                if (interest.is_sometimes() && new_interest.is_always())
1796                    || (interest.is_never() && !new_interest.is_never())
1797                {
1798                    interest = new_interest;
1799                }
1800            }
1801
1802            interest
1803        }
1804
1805        fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
1806            self.iter().all(|l| l.enabled(metadata, ctx.clone()))
1807        }
1808
1809        fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
1810            self.iter().all(|l| l.event_enabled(event, ctx.clone()))
1811        }
1812
1813        fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1814            for l in self {
1815                l.on_new_span(attrs, id, ctx.clone());
1816            }
1817        }
1818
1819        fn max_level_hint(&self) -> Option<LevelFilter> {
1820            // Default to `OFF` if there are no inner layers.
1821            let mut max_level = LevelFilter::OFF;
1822            for l in self {
1823                // NOTE(eliza): this is slightly subtle: if *any* layer
1824                // returns `None`, we have to return `None`, assuming there is
1825                // no max level hint, since that particular layer cannot
1826                // provide a hint.
1827                let hint = l.max_level_hint()?;
1828                max_level = core::cmp::max(hint, max_level);
1829            }
1830            Some(max_level)
1831        }
1832
1833        fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1834            for l in self {
1835                l.on_record(span, values, ctx.clone())
1836            }
1837        }
1838
1839        fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
1840            for l in self {
1841                l.on_follows_from(span, follows, ctx.clone());
1842            }
1843        }
1844
1845        fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
1846            for l in self {
1847                l.on_event(event, ctx.clone());
1848            }
1849        }
1850
1851        fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1852            for l in self {
1853                l.on_enter(id, ctx.clone());
1854            }
1855        }
1856
1857        fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1858            for l in self {
1859                l.on_exit(id, ctx.clone());
1860            }
1861        }
1862
1863        fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1864            for l in self {
1865                l.on_close(id.clone(), ctx.clone());
1866            }
1867        }
1868
1869        #[doc(hidden)]
1870        unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1871            // If downcasting to `Self`, return a pointer to `self`.
1872            if id == TypeId::of::<Self>() {
1873                return Some(self as *const _ as *const ());
1874            }
1875
1876            // Someone is looking for per-layer filters. But, this `Vec`
1877            // might contain layers with per-layer filters *and*
1878            // layers without filters. It should only be treated as a
1879            // per-layer-filtered layer if *all* its layers have
1880            // per-layer filters.
1881            // XXX(eliza): it's a bummer we have to do this linear search every
1882            // time. It would be nice if this could be cached, but that would
1883            // require replacing the `Vec` impl with an impl for a newtype...
1884            if filter::is_plf_downcast_marker(id) && self.iter().any(|s| s.downcast_raw(id).is_none()) {
1885                return None;
1886            }
1887
1888            // Otherwise, return the first child of `self` that downcaasts to
1889            // the selected type, if any.
1890            // XXX(eliza): hope this is reasonable lol
1891            self.iter().find_map(|l| l.downcast_raw(id))
1892        }
1893    }
1894}
1895
1896// === impl SubscriberExt ===
1897
1898impl<S: Subscriber> crate::sealed::Sealed for S {}
1899impl<S: Subscriber> SubscriberExt for S {}
1900
1901// === impl Identity ===
1902
1903impl<S: Subscriber> Layer<S> for Identity {}
1904
1905impl Identity {
1906    /// Returns a new `Identity` layer.
1907    pub fn new() -> Self {
1908        Self { _p: () }
1909    }
1910}