better_tracing/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 `better-tracing`'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 better_tracing::Layer;
40//! use better_tracing::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 better_tracing::{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 better_tracing::{Registry, prelude::*};
157//!
158//! let stdout_log = better_tracing::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 = better_tracing::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 better_tracing::{Registry, prelude::*};
192//!
193//! let stdout_log = better_tracing::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 = better_tracing::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 better_tracing::{
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 = better_tracing::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//! better_tracing::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 better_tracing::{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//! better_tracing::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 better_tracing::{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 = better_tracing::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 = better_tracing::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 = better_tracing::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//! better_tracing::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`] filters out _nothing_ (that is, allows everything through). For
473//! example:
474//!
475//! ```rust
476//! # use better_tracing::{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 better_tracing::{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 = better_tracing::fmt::layer();
518//!
519//! // Build a subscriber that combines the access log and stdout log
520//! // layers.
521//! better_tracing::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 better_tracing::{filter::{filter_fn, LevelFilter}, prelude::*};
534//!
535//! let access_log = // ...
536//!     # LevelFilter::INFO;
537//! let fmt_layer = better_tracing::fmt::layer();
538//!
539//! better_tracing::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 better_tracing::{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//! better_tracing::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 better_tracing::{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 = better_tracing::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 = better_tracing::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//! better_tracing::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 mod transform;
714pub use self::{context::*, layered::*, transform::*};
715
716// The `tests` module is `pub(crate)` because it contains test utilities used by
717// other modules.
718#[cfg(test)]
719pub(crate) mod tests;
720
721/// A composable handler for `tracing` events.
722///
723/// A `Layer` implements a behavior for recording or collecting traces that can
724/// be composed together with other `Layer`s to build a [`Subscriber`]. See the
725/// [module-level documentation](crate::layer) for details.
726///
727/// [`Subscriber`]: tracing_core::Subscriber
728#[cfg_attr(docsrs, doc(notable_trait))]
729pub trait Layer<S>
730where
731    S: Subscriber,
732    Self: 'static,
733{
734    /// Performs late initialization when installing this layer as a
735    /// [`Subscriber`].
736    ///
737    /// ## Avoiding Memory Leaks
738    ///
739    /// `Layer`s should not store the [`Dispatch`] pointing to the [`Subscriber`]
740    /// that they are a part of. Because the `Dispatch` owns the `Subscriber`,
741    /// storing the `Dispatch` within the `Subscriber` will create a reference
742    /// count cycle, preventing the `Dispatch` from ever being dropped.
743    ///
744    /// Instead, when it is necessary to store a cyclical reference to the
745    /// `Dispatch` within a `Layer`, use [`Dispatch::downgrade`] to convert a
746    /// `Dispatch` into a [`WeakDispatch`]. This type is analogous to
747    /// [`std::sync::Weak`], and does not create a reference count cycle. A
748    /// [`WeakDispatch`] can be stored within a subscriber without causing a
749    /// memory leak, and can be [upgraded] into a `Dispatch` temporarily when
750    /// the `Dispatch` must be accessed by the subscriber.
751    ///
752    /// [`WeakDispatch`]: tracing_core::dispatcher::WeakDispatch
753    /// [upgraded]: tracing_core::dispatcher::WeakDispatch::upgrade
754    /// [`Subscriber`]: tracing_core::Subscriber
755    fn on_register_dispatch(&self, subscriber: &Dispatch) {
756        let _ = subscriber;
757    }
758
759    /// Performs late initialization when attaching a `Layer` to a
760    /// [`Subscriber`].
761    ///
762    /// This is a callback that is called when the `Layer` is added to a
763    /// [`Subscriber`] (e.g. in [`Layer::with_subscriber`] and
764    /// [`SubscriberExt::with`]). Since this can only occur before the
765    /// [`Subscriber`] has been set as the default, both the `Layer` and
766    /// [`Subscriber`] are passed to this method _mutably_. This gives the
767    /// `Layer` the opportunity to set any of its own fields with values
768    /// received by method calls on the [`Subscriber`].
769    ///
770    /// For example, [`Filtered`] layers implement `on_layer` to call the
771    /// [`Subscriber`]'s [`register_filter`] method, and store the returned
772    /// [`FilterId`] as a field.
773    ///
774    /// **Note** In most cases, `Layer` implementations will not need to
775    /// implement this method. However, in cases where a type implementing
776    /// `Layer` wraps one or more other types that implement `Layer`, like the
777    /// [`Layered`] and [`Filtered`] types in this crate, that type MUST ensure
778    /// that the inner `Layer`s' `on_layer` methods are called. Otherwise,
779    /// functionality that relies on `on_layer`, such as [per-layer filtering],
780    /// may not work correctly.
781    ///
782    /// [`Filtered`]: crate::filter::Filtered
783    /// [`register_filter`]: crate::registry::LookupSpan::register_filter
784    /// [per-layer filtering]: #per-layer-filtering
785    /// [`FilterId`]: crate::filter::FilterId
786    fn on_layer(&mut self, subscriber: &mut S) {
787        let _ = subscriber;
788    }
789
790    /// Registers a new callsite with this layer, returning whether or not
791    /// the layer is interested in being notified about the callsite, similarly
792    /// to [`Subscriber::register_callsite`].
793    ///
794    /// By default, this returns [`Interest::always()`] if [`self.enabled`] returns
795    /// true, or [`Interest::never()`] if it returns false.
796    ///
797    /// <pre class="ignore" style="white-space:normal;font:inherit;">
798    /// <strong>Note</strong>: This method (and <a href="#method.enabled">
799    /// <code>Layer::enabled</code></a>) determine whether a span or event is
800    /// globally enabled, <em>not</em> whether the individual layer will be
801    /// notified about that span or event. This is intended to be used
802    /// by layers that implement filtering for the entire stack. Layers which do
803    /// not wish to be notified about certain spans or events but do not wish to
804    /// globally disable them should ignore those spans or events in their
805    /// <a href="#method.on_event"><code>on_event</code></a>,
806    /// <a href="#method.on_enter"><code>on_enter</code></a>,
807    /// <a href="#method.on_exit"><code>on_exit</code></a>, and other notification
808    /// methods.
809    /// </pre>
810    ///
811    /// See [the trait-level documentation] for more information on filtering
812    /// with `Layer`s.
813    ///
814    /// Layers may also implement this method to perform any behaviour that
815    /// should be run once per callsite. If the layer wishes to use
816    /// `register_callsite` for per-callsite behaviour, but does not want to
817    /// globally enable or disable those callsites, it should always return
818    /// [`Interest::always()`].
819    ///
820    /// [`Interest`]: tracing_core::Interest
821    /// [`Subscriber::register_callsite`]: tracing_core::Subscriber::register_callsite()
822    /// [`Interest::never()`]: tracing_core::subscriber::Interest::never()
823    /// [`Interest::always()`]: tracing_core::subscriber::Interest::always()
824    /// [`self.enabled`]: Layer::enabled()
825    /// [`Layer::enabled`]: Layer::enabled()
826    /// [`on_event`]: Layer::on_event()
827    /// [`on_enter`]: Layer::on_enter()
828    /// [`on_exit`]: Layer::on_exit()
829    /// [the trait-level documentation]: #filtering-with-layers
830    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
831        if self.enabled(metadata, Context::none()) {
832            Interest::always()
833        } else {
834            Interest::never()
835        }
836    }
837
838    /// Returns `true` if this layer is interested in a span or event with the
839    /// given `metadata` in the current [`Context`], similarly to
840    /// [`Subscriber::enabled`].
841    ///
842    /// By default, this always returns `true`, allowing the wrapped subscriber
843    /// to choose to disable the span.
844    ///
845    /// <pre class="ignore" style="white-space:normal;font:inherit;">
846    /// <strong>Note</strong>: This method (and <a href="#method.register_callsite">
847    /// <code>Layer::register_callsite</code></a>) determine whether a span or event is
848    /// globally enabled, <em>not</em> whether the individual layer will be
849    /// notified about that span or event. This is intended to be used
850    /// by layers that implement filtering for the entire stack. Layers which do
851    /// not wish to be notified about certain spans or events but do not wish to
852    /// globally disable them should ignore those spans or events in their
853    /// <a href="#method.on_event"><code>on_event</code></a>,
854    /// <a href="#method.on_enter"><code>on_enter</code></a>,
855    /// <a href="#method.on_exit"><code>on_exit</code></a>, and other notification
856    /// methods.
857    /// </pre>
858    ///
859    ///
860    /// See [the trait-level documentation] for more information on filtering
861    /// with `Layer`s.
862    ///
863    /// [`Interest`]: tracing_core::Interest
864    /// [`Subscriber::enabled`]: tracing_core::Subscriber::enabled()
865    /// [`Layer::register_callsite`]: Layer::register_callsite()
866    /// [`on_event`]: Layer::on_event()
867    /// [`on_enter`]: Layer::on_enter()
868    /// [`on_exit`]: Layer::on_exit()
869    /// [the trait-level documentation]: #filtering-with-layers
870    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
871        let _ = (metadata, ctx);
872        true
873    }
874
875    /// Notifies this layer that a new span was constructed with the given
876    /// `Attributes` and `Id`.
877    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
878        let _ = (attrs, id, ctx);
879    }
880
881    // TODO(eliza): do we want this to be a public API? If we end up moving
882    // filtering layers to a separate trait, we may no longer want `Layer`s to
883    // be able to participate in max level hinting...
884    #[doc(hidden)]
885    fn max_level_hint(&self) -> Option<LevelFilter> {
886        None
887    }
888
889    /// Notifies this layer that a span with the given `Id` recorded the given
890    /// `values`.
891    // Note: it's unclear to me why we'd need the current span in `record` (the
892    // only thing the `Context` type currently provides), but passing it in anyway
893    // seems like a good future-proofing measure as it may grow other methods later...
894    fn on_record(&self, _span: &span::Id, _values: &span::Record<'_>, _ctx: Context<'_, S>) {}
895
896    /// Notifies this layer that a span with the ID `span` recorded that it
897    /// follows from the span with the ID `follows`.
898    // Note: it's unclear to me why we'd need the current span in `record` (the
899    // only thing the `Context` type currently provides), but passing it in anyway
900    // seems like a good future-proofing measure as it may grow other methods later...
901    fn on_follows_from(&self, _span: &span::Id, _follows: &span::Id, _ctx: Context<'_, S>) {}
902
903    /// Called before [`on_event`], to determine if `on_event` should be called.
904    ///
905    /// <div class="example-wrap" style="display:inline-block">
906    /// <pre class="ignore" style="white-space:normal;font:inherit;">
907    ///
908    /// **Note**: This method determines whether an event is globally enabled,
909    /// *not* whether the individual `Layer` will be notified about the
910    /// event. This is intended to be used by `Layer`s that implement
911    /// filtering for the entire stack. `Layer`s which do not wish to be
912    /// notified about certain events but do not wish to globally disable them
913    /// should ignore those events in their [on_event][Self::on_event].
914    ///
915    /// </pre></div>
916    ///
917    /// See [the trait-level documentation] for more information on filtering
918    /// with `Layer`s.
919    ///
920    /// [`on_event`]: Self::on_event
921    /// [`Interest`]: tracing_core::Interest
922    /// [the trait-level documentation]: #filtering-with-layers
923    #[inline] // collapse this to a constant please mrs optimizer
924    fn event_enabled(&self, _event: &Event<'_>, _ctx: Context<'_, S>) -> bool {
925        true
926    }
927
928    /// Notifies this layer that an event has occurred.
929    fn on_event(&self, _event: &Event<'_>, _ctx: Context<'_, S>) {}
930
931    /// Notifies this layer that a span with the given ID was entered.
932    fn on_enter(&self, _id: &span::Id, _ctx: Context<'_, S>) {}
933
934    /// Notifies this layer that the span with the given ID was exited.
935    fn on_exit(&self, _id: &span::Id, _ctx: Context<'_, S>) {}
936
937    /// Notifies this layer that the span with the given ID has been closed.
938    fn on_close(&self, _id: span::Id, _ctx: Context<'_, S>) {}
939
940    /// Notifies this layer that a span ID has been cloned, and that the
941    /// subscriber returned a different ID.
942    fn on_id_change(&self, _old: &span::Id, _new: &span::Id, _ctx: Context<'_, S>) {}
943
944    /// Composes this layer around the given `Layer`, returning a `Layered`
945    /// struct implementing `Layer`.
946    ///
947    /// The returned `Layer` will call the methods on this `Layer` and then
948    /// those of the new `Layer`, before calling the methods on the subscriber
949    /// it wraps. For example:
950    ///
951    /// ```rust
952    /// # use better_tracing::layer::Layer;
953    /// # use tracing_core::Subscriber;
954    /// pub struct FooLayer {
955    ///     // ...
956    /// }
957    ///
958    /// pub struct BarLayer {
959    ///     // ...
960    /// }
961    ///
962    /// pub struct MySubscriber {
963    ///     // ...
964    /// }
965    ///
966    /// impl<S: Subscriber> Layer<S> for FooLayer {
967    ///     // ...
968    /// }
969    ///
970    /// impl<S: Subscriber> Layer<S> for BarLayer {
971    ///     // ...
972    /// }
973    ///
974    /// # impl FooLayer {
975    /// # fn new() -> Self { Self {} }
976    /// # }
977    /// # impl BarLayer {
978    /// # fn new() -> Self { Self { }}
979    /// # }
980    /// # impl MySubscriber {
981    /// # fn new() -> Self { Self { }}
982    /// # }
983    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
984    /// # impl tracing_core::Subscriber for MySubscriber {
985    /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
986    /// #   fn record(&self, _: &Id, _: &Record) {}
987    /// #   fn event(&self, _: &Event) {}
988    /// #   fn record_follows_from(&self, _: &Id, _: &Id) {}
989    /// #   fn enabled(&self, _: &Metadata) -> bool { false }
990    /// #   fn enter(&self, _: &Id) {}
991    /// #   fn exit(&self, _: &Id) {}
992    /// # }
993    /// let subscriber = FooLayer::new()
994    ///     .and_then(BarLayer::new())
995    ///     .with_subscriber(MySubscriber::new());
996    /// ```
997    ///
998    /// Multiple layers may be composed in this manner:
999    ///
1000    /// ```rust
1001    /// # use better_tracing::layer::Layer;
1002    /// # use tracing_core::Subscriber;
1003    /// # pub struct FooLayer {}
1004    /// # pub struct BarLayer {}
1005    /// # pub struct MySubscriber {}
1006    /// # impl<S: Subscriber> Layer<S> for FooLayer {}
1007    /// # impl<S: Subscriber> Layer<S> for BarLayer {}
1008    /// # impl FooLayer {
1009    /// # fn new() -> Self { Self {} }
1010    /// # }
1011    /// # impl BarLayer {
1012    /// # fn new() -> Self { Self { }}
1013    /// # }
1014    /// # impl MySubscriber {
1015    /// # fn new() -> Self { Self { }}
1016    /// # }
1017    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
1018    /// # impl tracing_core::Subscriber for MySubscriber {
1019    /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
1020    /// #   fn record(&self, _: &Id, _: &Record) {}
1021    /// #   fn event(&self, _: &Event) {}
1022    /// #   fn record_follows_from(&self, _: &Id, _: &Id) {}
1023    /// #   fn enabled(&self, _: &Metadata) -> bool { false }
1024    /// #   fn enter(&self, _: &Id) {}
1025    /// #   fn exit(&self, _: &Id) {}
1026    /// # }
1027    /// pub struct BazLayer {
1028    ///     // ...
1029    /// }
1030    ///
1031    /// impl<S: Subscriber> Layer<S> for BazLayer {
1032    ///     // ...
1033    /// }
1034    /// # impl BazLayer { fn new() -> Self { BazLayer {} } }
1035    ///
1036    /// let subscriber = FooLayer::new()
1037    ///     .and_then(BarLayer::new())
1038    ///     .and_then(BazLayer::new())
1039    ///     .with_subscriber(MySubscriber::new());
1040    /// ```
1041    fn and_then<L>(self, layer: L) -> Layered<L, Self, S>
1042    where
1043        L: Layer<S>,
1044        Self: Sized,
1045    {
1046        let inner_has_layer_filter = filter::layer_has_plf(&self);
1047        Layered::new(layer, self, inner_has_layer_filter)
1048    }
1049
1050    /// Composes this `Layer` with the given [`Subscriber`], returning a
1051    /// `Layered` struct that implements [`Subscriber`].
1052    ///
1053    /// The returned `Layered` subscriber will call the methods on this `Layer`
1054    /// and then those of the wrapped subscriber.
1055    ///
1056    /// For example:
1057    /// ```rust
1058    /// # use better_tracing::layer::Layer;
1059    /// # use tracing_core::Subscriber;
1060    /// pub struct FooLayer {
1061    ///     // ...
1062    /// }
1063    ///
1064    /// pub struct MySubscriber {
1065    ///     // ...
1066    /// }
1067    ///
1068    /// impl<S: Subscriber> Layer<S> for FooLayer {
1069    ///     // ...
1070    /// }
1071    ///
1072    /// # impl FooLayer {
1073    /// # fn new() -> Self { Self {} }
1074    /// # }
1075    /// # impl MySubscriber {
1076    /// # fn new() -> Self { Self { }}
1077    /// # }
1078    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata};
1079    /// # impl tracing_core::Subscriber for MySubscriber {
1080    /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
1081    /// #   fn record(&self, _: &Id, _: &Record) {}
1082    /// #   fn event(&self, _: &tracing_core::Event) {}
1083    /// #   fn record_follows_from(&self, _: &Id, _: &Id) {}
1084    /// #   fn enabled(&self, _: &Metadata) -> bool { false }
1085    /// #   fn enter(&self, _: &Id) {}
1086    /// #   fn exit(&self, _: &Id) {}
1087    /// # }
1088    /// let subscriber = FooLayer::new()
1089    ///     .with_subscriber(MySubscriber::new());
1090    ///```
1091    ///
1092    /// [`Subscriber`]: tracing_core::Subscriber
1093    fn with_subscriber(mut self, mut inner: S) -> Layered<Self, S>
1094    where
1095        Self: Sized,
1096    {
1097        let inner_has_layer_filter = filter::subscriber_has_plf(&inner);
1098        self.on_layer(&mut inner);
1099        Layered::new(self, inner, inner_has_layer_filter)
1100    }
1101
1102    /// Combines `self` with a [`Filter`], returning a [`Filtered`] layer.
1103    ///
1104    /// The [`Filter`] will control which spans and events are enabled for
1105    /// this layer. See [the trait-level documentation][plf] for details on
1106    /// per-layer filtering.
1107    ///
1108    /// [`Filtered`]: crate::filter::Filtered
1109    /// [plf]: crate::layer#per-layer-filtering
1110    #[cfg(all(feature = "registry", feature = "std"))]
1111    #[cfg_attr(docsrs, doc(cfg(all(feature = "registry", feature = "std"))))]
1112    fn with_filter<F>(self, filter: F) -> filter::Filtered<Self, F, S>
1113    where
1114        Self: Sized,
1115        F: Filter<S>,
1116    {
1117        filter::Filtered::new(self, filter)
1118    }
1119
1120    /// Erases the type of this [`Layer`], returning a [`Box`]ed `dyn
1121    /// Layer` trait object.
1122    ///
1123    /// This can be used when a function returns a `Layer` which may be of
1124    /// one of several types, or when a `Layer` subscriber has a very long type
1125    /// signature.
1126    ///
1127    /// # Examples
1128    ///
1129    /// The following example will *not* compile, because the value assigned to
1130    /// `log_layer` may have one of several different types:
1131    ///
1132    /// ```compile_fail
1133    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1134    /// use better_tracing::{Layer, filter::LevelFilter, prelude::*};
1135    /// use std::{path::PathBuf, fs::File, io};
1136    ///
1137    /// /// Configures whether logs are emitted to a file, to stdout, or to stderr.
1138    /// pub enum LogConfig {
1139    ///     File(PathBuf),
1140    ///     Stdout,
1141    ///     Stderr,
1142    /// }
1143    ///
1144    /// let config = // ...
1145    ///     # LogConfig::Stdout;
1146    ///
1147    /// // Depending on the config, construct a layer of one of several types.
1148    /// let log_layer = match config {
1149    ///     // If logging to a file, use a maximally-verbose configuration.
1150    ///     LogConfig::File(path) => {
1151    ///         let file = File::create(path)?;
1152    ///         better_tracing::fmt::layer()
1153    ///             .with_thread_ids(true)
1154    ///             .with_thread_names(true)
1155    ///             // Selecting the JSON logging format changes the layer's
1156    ///             // type.
1157    ///             .json()
1158    ///             .with_span_list(true)
1159    ///             // Setting the writer to use our log file changes the
1160    ///             // layer's type again.
1161    ///             .with_writer(file)
1162    ///     },
1163    ///
1164    ///     // If logging to stdout, use a pretty, human-readable configuration.
1165    ///     LogConfig::Stdout => better_tracing::fmt::layer()
1166    ///         // Selecting the "pretty" logging format changes the
1167    ///         // layer's type!
1168    ///         .pretty()
1169    ///         .with_writer(io::stdout)
1170    ///         // Add a filter based on the RUST_LOG environment variable;
1171    ///         // this changes the type too!
1172    ///         .and_then(better_tracing::EnvFilter::from_default_env()),
1173    ///
1174    ///     // If logging to stdout, only log errors and warnings.
1175    ///     LogConfig::Stderr => better_tracing::fmt::layer()
1176    ///         // Changing the writer changes the layer's type
1177    ///         .with_writer(io::stderr)
1178    ///         // Only log the `WARN` and `ERROR` levels. Adding a filter
1179    ///         // changes the layer's type to `Filtered<LevelFilter, ...>`.
1180    ///         .with_filter(LevelFilter::WARN),
1181    /// };
1182    ///
1183    /// better_tracing::registry()
1184    ///     .with(log_layer)
1185    ///     .init();
1186    /// # Ok(()) }
1187    /// ```
1188    ///
1189    /// However, adding a call to `.boxed()` after each match arm erases the
1190    /// layer's type, so this code *does* compile:
1191    ///
1192    /// ```
1193    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1194    /// # use better_tracing::{Layer, EnvFilter, filter::LevelFilter, prelude::*};
1195    /// # use std::{path::PathBuf, fs::File, io};
1196    /// # pub enum LogConfig {
1197    /// #    File(PathBuf),
1198    /// #    Stdout,
1199    /// #    Stderr,
1200    /// # }
1201    /// # let config = LogConfig::Stdout;
1202    /// let log_layer = match config {
1203    ///     LogConfig::File(path) => {
1204    ///         let file = File::create(path)?;
1205    ///         better_tracing::fmt::layer()
1206    ///             .with_thread_ids(true)
1207    ///             .with_thread_names(true)
1208    ///             .json()
1209    ///             .with_span_list(true)
1210    ///             .with_writer(file)
1211    ///             // Erase the type by boxing the layer
1212    ///             .boxed()
1213    ///     },
1214    ///
1215    ///     LogConfig::Stdout => better_tracing::fmt::layer()
1216    ///         .pretty()
1217    ///         .with_writer(io::stdout)
1218    ///         .and_then(better_tracing::EnvFilter::from_default_env())
1219    ///         // Erase the type by boxing the layer
1220    ///         .boxed(),
1221    ///
1222    ///     LogConfig::Stderr => better_tracing::fmt::layer()
1223    ///         .with_writer(io::stderr)
1224    ///         .with_filter(LevelFilter::WARN)
1225    ///         // Erase the type by boxing the layer
1226    ///         .boxed(),
1227    /// };
1228    ///
1229    /// better_tracing::registry()
1230    ///     .with(log_layer)
1231    ///     .init();
1232    /// # Ok(()) }
1233    /// ```
1234    #[cfg(any(feature = "alloc", feature = "std"))]
1235    #[cfg_attr(docsrs, doc(cfg(any(feature = "alloc", feature = "std"))))]
1236    fn boxed(self) -> Box<dyn Layer<S> + Send + Sync + 'static>
1237    where
1238        Self: Sized,
1239        Self: Layer<S> + Send + Sync + 'static,
1240        S: Subscriber,
1241    {
1242        Box::new(self)
1243    }
1244
1245    #[doc(hidden)]
1246    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1247        if id == TypeId::of::<Self>() {
1248            Some(self as *const _ as *const ())
1249        } else {
1250            None
1251        }
1252    }
1253}
1254
1255feature! {
1256    #![all(feature = "registry", feature = "std")]
1257
1258    /// A per-[`Layer`] filter that determines whether a span or event is enabled
1259    /// for an individual layer.
1260    ///
1261    /// See [the module-level documentation][plf] for details on using [`Filter`]s.
1262    ///
1263    /// [plf]: crate::layer#per-layer-filtering
1264    #[cfg_attr(docsrs, doc(notable_trait))]
1265    pub trait Filter<S> {
1266        /// Returns `true` if this layer is interested in a span or event with the
1267        /// given [`Metadata`] in the current [`Context`], similarly to
1268        /// [`Subscriber::enabled`].
1269        ///
1270        /// If this returns `false`, the span or event will be disabled _for the
1271        /// wrapped [`Layer`]_. Unlike [`Layer::enabled`], the span or event will
1272        /// still be recorded if any _other_ layers choose to enable it. However,
1273        /// the layer [filtered] by this filter will skip recording that span or
1274        /// event.
1275        ///
1276        /// If all layers indicate that they do not wish to see this span or event,
1277        /// it will be disabled.
1278        ///
1279        /// [`metadata`]: tracing_core::Metadata
1280        /// [`Subscriber::enabled`]: tracing_core::Subscriber::enabled
1281        /// [filtered]: crate::filter::Filtered
1282        fn enabled(&self, meta: &Metadata<'_>, cx: &Context<'_, S>) -> bool;
1283
1284        /// Returns an [`Interest`] indicating whether this layer will [always],
1285        /// [sometimes], or [never] be interested in the given [`Metadata`].
1286        ///
1287        /// When a given callsite will [always] or [never] be enabled, the results
1288        /// of evaluating the filter may be cached for improved performance.
1289        /// Therefore, if a filter is capable of determining that it will always or
1290        /// never enable a particular callsite, providing an implementation of this
1291        /// function is recommended.
1292        ///
1293        /// <pre class="ignore" style="white-space:normal;font:inherit;">
1294        /// <strong>Note</strong>: If a <code>Filter</code> will perform
1295        /// <em>dynamic filtering</em> that depends on the current context in which
1296        /// a span or event was observed (e.g. only enabling an event when it
1297        /// occurs within a particular span), it <strong>must</strong> return
1298        /// <code>Interest::sometimes()</code> from this method. If it returns
1299        /// <code>Interest::always()</code> or <code>Interest::never()</code>, the
1300        /// <code>enabled</code> method may not be called when a particular instance
1301        /// of that span or event is recorded.
1302        /// </pre>
1303        ///
1304        /// This method is broadly similar to [`Subscriber::register_callsite`];
1305        /// however, since the returned value represents only the interest of
1306        /// *this* layer, the resulting behavior is somewhat different.
1307        ///
1308        /// If a [`Subscriber`] returns [`Interest::always()`][always] or
1309        /// [`Interest::never()`][never] for a given [`Metadata`], its [`enabled`]
1310        /// method is then *guaranteed* to never be called for that callsite. On the
1311        /// other hand, when a `Filter` returns [`Interest::always()`][always] or
1312        /// [`Interest::never()`][never] for a callsite, _other_ [`Layer`]s may have
1313        /// differing interests in that callsite. If this is the case, the callsite
1314        /// will receive [`Interest::sometimes()`][sometimes], and the [`enabled`]
1315        /// method will still be called for that callsite when it records a span or
1316        /// event.
1317        ///
1318        /// Returning [`Interest::always()`][always] or [`Interest::never()`][never] from
1319        /// `Filter::callsite_enabled` will permanently enable or disable a
1320        /// callsite (without requiring subsequent calls to [`enabled`]) if and only
1321        /// if the following is true:
1322        ///
1323        /// - all [`Layer`]s that comprise the subscriber include `Filter`s
1324        ///   (this includes a tree of [`Layered`] layers that share the same
1325        ///   `Filter`)
1326        /// - all those `Filter`s return the same [`Interest`].
1327        ///
1328        /// For example, if a [`Subscriber`] consists of two [`Filtered`] layers,
1329        /// and both of those layers return [`Interest::never()`][never], that
1330        /// callsite *will* never be enabled, and the [`enabled`] methods of those
1331        /// [`Filter`]s will not be called.
1332        ///
1333        /// ## Default Implementation
1334        ///
1335        /// The default implementation of this method assumes that the
1336        /// `Filter`'s [`enabled`] method _may_ perform dynamic filtering, and
1337        /// returns [`Interest::sometimes()`][sometimes], to ensure that [`enabled`]
1338        /// is called to determine whether a particular _instance_ of the callsite
1339        /// is enabled in the current context. If this is *not* the case, and the
1340        /// `Filter`'s [`enabled`] method will always return the same result
1341        /// for a particular [`Metadata`], this method can be overridden as
1342        /// follows:
1343        ///
1344        /// ```
1345        /// use better_tracing::layer;
1346        /// use tracing_core::{Metadata, subscriber::Interest};
1347        ///
1348        /// struct MyFilter {
1349        ///     // ...
1350        /// }
1351        ///
1352        /// impl MyFilter {
1353        ///     // The actual logic for determining whether a `Metadata` is enabled
1354        ///     // must be factored out from the `enabled` method, so that it can be
1355        ///     // called without a `Context` (which is not provided to the
1356        ///     // `callsite_enabled` method).
1357        ///     fn is_enabled(&self, metadata: &Metadata<'_>) -> bool {
1358        ///         // ...
1359        ///         # drop(metadata); true
1360        ///     }
1361        /// }
1362        ///
1363        /// impl<S> layer::Filter<S> for MyFilter {
1364        ///     fn enabled(&self, metadata: &Metadata<'_>, _: &layer::Context<'_, S>) -> bool {
1365        ///         // Even though we are implementing `callsite_enabled`, we must still provide a
1366        ///         // working implementation of `enabled`, as returning `Interest::always()` or
1367        ///         // `Interest::never()` will *allow* caching, but will not *guarantee* it.
1368        ///         // Other filters may still return `Interest::sometimes()`, so we may be
1369        ///         // asked again in `enabled`.
1370        ///         self.is_enabled(metadata)
1371        ///     }
1372        ///
1373        ///     fn callsite_enabled(&self, metadata: &'static Metadata<'static>) -> Interest {
1374        ///         // The result of `self.enabled(metadata, ...)` will always be
1375        ///         // the same for any given `Metadata`, so we can convert it into
1376        ///         // an `Interest`:
1377        ///         if self.is_enabled(metadata) {
1378        ///             Interest::always()
1379        ///         } else {
1380        ///             Interest::never()
1381        ///         }
1382        ///     }
1383        /// }
1384        /// ```
1385        ///
1386        /// [`Metadata`]: tracing_core::Metadata
1387        /// [`Interest`]: tracing_core::Interest
1388        /// [always]: tracing_core::Interest::always
1389        /// [sometimes]: tracing_core::Interest::sometimes
1390        /// [never]: tracing_core::Interest::never
1391        /// [`Subscriber::register_callsite`]: tracing_core::Subscriber::register_callsite
1392        /// [`Subscriber`]: tracing_core::Subscriber
1393        /// [`enabled`]: Filter::enabled
1394        /// [`Filtered`]: crate::filter::Filtered
1395        fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
1396            let _ = meta;
1397            Interest::sometimes()
1398        }
1399
1400        /// Called before the filtered [`Layer]'s [`on_event`], to determine if
1401        /// `on_event` should be called.
1402        ///
1403        /// This gives a chance to filter events based on their fields. Note,
1404        /// however, that this *does not* override [`enabled`], and is not even
1405        /// called if [`enabled`] returns `false`.
1406        ///
1407        /// ## Default Implementation
1408        ///
1409        /// By default, this method returns `true`, indicating that no events are
1410        /// filtered out based on their fields.
1411        ///
1412        /// [`enabled`]: crate::layer::Filter::enabled
1413        /// [`on_event`]: crate::layer::Layer::on_event
1414        #[inline] // collapse this to a constant please mrs optimizer
1415        fn event_enabled(&self, event: &Event<'_>, cx: &Context<'_, S>) -> bool {
1416            let _ = (event, cx);
1417            true
1418        }
1419
1420        /// Returns an optional hint of the highest [verbosity level][level] that
1421        /// this `Filter` will enable.
1422        ///
1423        /// If this method returns a [`LevelFilter`], it will be used as a hint to
1424        /// determine the most verbose level that will be enabled. This will allow
1425        /// spans and events which are more verbose than that level to be skipped
1426        /// more efficiently. An implementation of this method is optional, but
1427        /// strongly encouraged.
1428        ///
1429        /// If the maximum level the `Filter` will enable can change over the
1430        /// course of its lifetime, it is free to return a different value from
1431        /// multiple invocations of this method. However, note that changes in the
1432        /// maximum level will **only** be reflected after the callsite [`Interest`]
1433        /// cache is rebuilt, by calling the
1434        /// [`tracing_core::callsite::rebuild_interest_cache`][rebuild] function.
1435        /// Therefore, if the `Filter will change the value returned by this
1436        /// method, it is responsible for ensuring that
1437        /// [`rebuild_interest_cache`][rebuild] is called after the value of the max
1438        /// level changes.
1439        ///
1440        /// ## Default Implementation
1441        ///
1442        /// By default, this method returns `None`, indicating that the maximum
1443        /// level is unknown.
1444        ///
1445        /// [level]: tracing_core::metadata::Level
1446        /// [`LevelFilter`]: crate::filter::LevelFilter
1447        /// [`Interest`]: tracing_core::subscriber::Interest
1448        /// [rebuild]: tracing_core::callsite::rebuild_interest_cache
1449        fn max_level_hint(&self) -> Option<LevelFilter> {
1450            None
1451        }
1452
1453        /// Notifies this filter that a new span was constructed with the given
1454        /// `Attributes` and `Id`.
1455        ///
1456        /// By default, this method does nothing. `Filter` implementations that
1457        /// need to be notified when new spans are created can override this
1458        /// method.
1459        fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1460            let _ = (attrs, id, ctx);
1461        }
1462
1463
1464        /// Notifies this filter that a span with the given `Id` recorded the given
1465        /// `values`.
1466        ///
1467        /// By default, this method does nothing. `Filter` implementations that
1468        /// need to be notified when new spans are created can override this
1469        /// method.
1470        fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1471            let _ = (id, values, ctx);
1472        }
1473
1474        /// Notifies this filter that a span with the given ID was entered.
1475        ///
1476        /// By default, this method does nothing. `Filter` implementations that
1477        /// need to be notified when a span is entered can override this method.
1478        fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1479            let _ = (id, ctx);
1480        }
1481
1482        /// Notifies this filter that a span with the given ID was exited.
1483        ///
1484        /// By default, this method does nothing. `Filter` implementations that
1485        /// need to be notified when a span is exited can override this method.
1486        fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1487            let _ = (id, ctx);
1488        }
1489
1490        /// Notifies this filter that a span with the given ID has been closed.
1491        ///
1492        /// By default, this method does nothing. `Filter` implementations that
1493        /// need to be notified when a span is closed can override this method.
1494        fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1495            let _ = (id, ctx);
1496        }
1497    }
1498}
1499
1500/// Extension trait adding a `with(Layer)` combinator to `Subscriber`s.
1501pub trait SubscriberExt: Subscriber + crate::sealed::Sealed {
1502    /// Wraps `self` with the provided `layer`.
1503    fn with<L>(self, layer: L) -> Layered<L, Self>
1504    where
1505        L: Layer<Self>,
1506        Self: Sized,
1507    {
1508        layer.with_subscriber(self)
1509    }
1510}
1511
1512/// A layer that does nothing.
1513#[derive(Clone, Debug, Default)]
1514pub struct Identity {
1515    _p: (),
1516}
1517
1518// === impl Layer ===
1519
1520#[derive(Clone, Copy)]
1521pub(crate) struct NoneLayerMarker(());
1522static NONE_LAYER_MARKER: NoneLayerMarker = NoneLayerMarker(());
1523
1524/// Is a type implementing `Layer` `Option::<_>::None`?
1525pub(crate) fn layer_is_none<L, S>(layer: &L) -> bool
1526where
1527    L: Layer<S>,
1528    S: Subscriber,
1529{
1530    unsafe {
1531        // Safety: we're not actually *doing* anything with this pointer ---
1532        // this only care about the `Option`, which is essentially being used
1533        // as a bool. We can rely on the pointer being valid, because it is
1534        // a crate-private type, and is only returned by the `Layer` impl
1535        // for `Option`s. However, even if the layer *does* decide to be
1536        // evil and give us an invalid pointer here, that's fine, because we'll
1537        // never actually dereference it.
1538        layer.downcast_raw(TypeId::of::<NoneLayerMarker>())
1539    }
1540    .is_some()
1541}
1542
1543/// Is a type implementing `Subscriber` `Option::<_>::None`?
1544pub(crate) fn subscriber_is_none<S>(subscriber: &S) -> bool
1545where
1546    S: Subscriber,
1547{
1548    unsafe {
1549        // Safety: we're not actually *doing* anything with this pointer ---
1550        // this only care about the `Option`, which is essentially being used
1551        // as a bool. We can rely on the pointer being valid, because it is
1552        // a crate-private type, and is only returned by the `Layer` impl
1553        // for `Option`s. However, even if the subscriber *does* decide to be
1554        // evil and give us an invalid pointer here, that's fine, because we'll
1555        // never actually dereference it.
1556        subscriber.downcast_raw(TypeId::of::<NoneLayerMarker>())
1557    }
1558    .is_some()
1559}
1560
1561impl<L, S> Layer<S> for Option<L>
1562where
1563    L: Layer<S>,
1564    S: Subscriber,
1565{
1566    fn on_layer(&mut self, subscriber: &mut S) {
1567        if let Some(ref mut layer) = self {
1568            layer.on_layer(subscriber)
1569        }
1570    }
1571
1572    #[inline]
1573    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1574        if let Some(ref inner) = self {
1575            inner.on_new_span(attrs, id, ctx)
1576        }
1577    }
1578
1579    #[inline]
1580    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
1581        match self {
1582            Some(ref inner) => inner.register_callsite(metadata),
1583            None => Interest::always(),
1584        }
1585    }
1586
1587    #[inline]
1588    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
1589        match self {
1590            Some(ref inner) => inner.enabled(metadata, ctx),
1591            None => true,
1592        }
1593    }
1594
1595    #[inline]
1596    fn max_level_hint(&self) -> Option<LevelFilter> {
1597        match self {
1598            Some(ref inner) => inner.max_level_hint(),
1599            None => {
1600                // There is no inner layer, so this layer will
1601                // never enable anything.
1602                Some(LevelFilter::OFF)
1603            }
1604        }
1605    }
1606
1607    #[inline]
1608    fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1609        if let Some(ref inner) = self {
1610            inner.on_record(span, values, ctx);
1611        }
1612    }
1613
1614    #[inline]
1615    fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
1616        if let Some(ref inner) = self {
1617            inner.on_follows_from(span, follows, ctx);
1618        }
1619    }
1620
1621    #[inline]
1622    fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
1623        match self {
1624            Some(ref inner) => inner.event_enabled(event, ctx),
1625            None => true,
1626        }
1627    }
1628
1629    #[inline]
1630    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
1631        if let Some(ref inner) = self {
1632            inner.on_event(event, ctx);
1633        }
1634    }
1635
1636    #[inline]
1637    fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1638        if let Some(ref inner) = self {
1639            inner.on_enter(id, ctx);
1640        }
1641    }
1642
1643    #[inline]
1644    fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1645        if let Some(ref inner) = self {
1646            inner.on_exit(id, ctx);
1647        }
1648    }
1649
1650    #[inline]
1651    fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1652        if let Some(ref inner) = self {
1653            inner.on_close(id, ctx);
1654        }
1655    }
1656
1657    #[inline]
1658    fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
1659        if let Some(ref inner) = self {
1660            inner.on_id_change(old, new, ctx)
1661        }
1662    }
1663
1664    #[doc(hidden)]
1665    #[inline]
1666    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1667        if id == TypeId::of::<Self>() {
1668            Some(self as *const _ as *const ())
1669        } else if id == TypeId::of::<NoneLayerMarker>() && self.is_none() {
1670            Some(&NONE_LAYER_MARKER as *const _ as *const ())
1671        } else {
1672            self.as_ref().and_then(|inner| inner.downcast_raw(id))
1673        }
1674    }
1675}
1676
1677feature! {
1678    #![any(feature = "std", feature = "alloc")]
1679    #[cfg(not(feature = "std"))]
1680    use alloc::vec::Vec;
1681
1682    macro_rules! layer_impl_body {
1683        () => {
1684            #[inline]
1685            fn on_register_dispatch(&self, subscriber: &Dispatch) {
1686                self.deref().on_register_dispatch(subscriber);
1687            }
1688
1689            #[inline]
1690            fn on_layer(&mut self, subscriber: &mut S) {
1691                self.deref_mut().on_layer(subscriber);
1692            }
1693
1694            #[inline]
1695            fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1696                self.deref().on_new_span(attrs, id, ctx)
1697            }
1698
1699            #[inline]
1700            fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
1701                self.deref().register_callsite(metadata)
1702            }
1703
1704            #[inline]
1705            fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
1706                self.deref().enabled(metadata, ctx)
1707            }
1708
1709            #[inline]
1710            fn max_level_hint(&self) -> Option<LevelFilter> {
1711                self.deref().max_level_hint()
1712            }
1713
1714            #[inline]
1715            fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1716                self.deref().on_record(span, values, ctx)
1717            }
1718
1719            #[inline]
1720            fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
1721                self.deref().on_follows_from(span, follows, ctx)
1722            }
1723
1724            #[inline]
1725            fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
1726                self.deref().event_enabled(event, ctx)
1727            }
1728
1729            #[inline]
1730            fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
1731                self.deref().on_event(event, ctx)
1732            }
1733
1734            #[inline]
1735            fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1736                self.deref().on_enter(id, ctx)
1737            }
1738
1739            #[inline]
1740            fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1741                self.deref().on_exit(id, ctx)
1742            }
1743
1744            #[inline]
1745            fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1746                self.deref().on_close(id, ctx)
1747            }
1748
1749            #[inline]
1750            fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
1751                self.deref().on_id_change(old, new, ctx)
1752            }
1753
1754            #[doc(hidden)]
1755            #[inline]
1756            unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1757                self.deref().downcast_raw(id)
1758            }
1759        };
1760    }
1761
1762    impl<L, S> Layer<S> for Box<L>
1763    where
1764        L: Layer<S>,
1765        S: Subscriber,
1766    {
1767        layer_impl_body! {}
1768    }
1769
1770    impl<S> Layer<S> for Box<dyn Layer<S> + Send + Sync>
1771    where
1772        S: Subscriber,
1773    {
1774        layer_impl_body! {}
1775    }
1776
1777
1778
1779    impl<S, L> Layer<S> for Vec<L>
1780    where
1781        L: Layer<S>,
1782        S: Subscriber,
1783    {
1784
1785        fn on_layer(&mut self, subscriber: &mut S) {
1786            for l in self {
1787                l.on_layer(subscriber);
1788            }
1789        }
1790
1791        fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
1792            // Return highest level of interest.
1793            let mut interest = Interest::never();
1794            for l in self {
1795                let new_interest = l.register_callsite(metadata);
1796                if (interest.is_sometimes() && new_interest.is_always())
1797                    || (interest.is_never() && !new_interest.is_never())
1798                {
1799                    interest = new_interest;
1800                }
1801            }
1802
1803            interest
1804        }
1805
1806        fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
1807            self.iter().all(|l| l.enabled(metadata, ctx.clone()))
1808        }
1809
1810        fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
1811            self.iter().all(|l| l.event_enabled(event, ctx.clone()))
1812        }
1813
1814        fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1815            for l in self {
1816                l.on_new_span(attrs, id, ctx.clone());
1817            }
1818        }
1819
1820        fn max_level_hint(&self) -> Option<LevelFilter> {
1821            // Default to `OFF` if there are no inner layers.
1822            let mut max_level = LevelFilter::OFF;
1823            for l in self {
1824                // NOTE(eliza): this is slightly subtle: if *any* layer
1825                // returns `None`, we have to return `None`, assuming there is
1826                // no max level hint, since that particular layer cannot
1827                // provide a hint.
1828                let hint = l.max_level_hint()?;
1829                max_level = core::cmp::max(hint, max_level);
1830            }
1831            Some(max_level)
1832        }
1833
1834        fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1835            for l in self {
1836                l.on_record(span, values, ctx.clone())
1837            }
1838        }
1839
1840        fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
1841            for l in self {
1842                l.on_follows_from(span, follows, ctx.clone());
1843            }
1844        }
1845
1846        fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
1847            for l in self {
1848                l.on_event(event, ctx.clone());
1849            }
1850        }
1851
1852        fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1853            for l in self {
1854                l.on_enter(id, ctx.clone());
1855            }
1856        }
1857
1858        fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1859            for l in self {
1860                l.on_exit(id, ctx.clone());
1861            }
1862        }
1863
1864        fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1865            for l in self {
1866                l.on_close(id.clone(), ctx.clone());
1867            }
1868        }
1869
1870        #[doc(hidden)]
1871        unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1872            // If downcasting to `Self`, return a pointer to `self`.
1873            if id == TypeId::of::<Self>() {
1874                return Some(self as *const _ as *const ());
1875            }
1876
1877            // Someone is looking for per-layer filters. But, this `Vec`
1878            // might contain layers with per-layer filters *and*
1879            // layers without filters. It should only be treated as a
1880            // per-layer-filtered layer if *all* its layers have
1881            // per-layer filters.
1882            // XXX(eliza): it's a bummer we have to do this linear search every
1883            // time. It would be nice if this could be cached, but that would
1884            // require replacing the `Vec` impl with an impl for a newtype...
1885            if filter::is_plf_downcast_marker(id) && self.iter().any(|s| s.downcast_raw(id).is_none()) {
1886                return None;
1887            }
1888
1889            // Otherwise, return the first child of `self` that downcaasts to
1890            // the selected type, if any.
1891            // XXX(eliza): hope this is reasonable lol
1892            self.iter().find_map(|l| l.downcast_raw(id))
1893        }
1894    }
1895}
1896
1897// === impl SubscriberExt ===
1898
1899impl<S: Subscriber> crate::sealed::Sealed for S {}
1900impl<S: Subscriber> SubscriberExt for S {}
1901
1902// === impl Identity ===
1903
1904impl<S: Subscriber> Layer<S> for Identity {}
1905
1906impl Identity {
1907    /// Returns a new `Identity` layer.
1908    pub fn new() -> Self {
1909        Self { _p: () }
1910    }
1911}