]> git.proxmox.com Git - rustc.git/blame - vendor/tracing-subscriber/src/layer/mod.rs
New upstream version 1.64.0+dfsg1
[rustc.git] / vendor / tracing-subscriber / src / layer / mod.rs
CommitLineData
c295e0f8
XL
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//!
3c0e092e 9//! In particular, [`Subscriber`]s are responsible for generating [span IDs] and
c295e0f8
XL
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//!
04454e1e 22//! # Composing Layers
c295e0f8
XL
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//!
04454e1e
FG
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
064997fb 271//! [`Vec<L> where L: Layer` also implements `Layer`][vec-impl]. This
04454e1e
FG
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
064997fb 373//! [vec-impl]: Layer#impl-Layer<S>-for-Vec<L>
c295e0f8
XL
374//! [prelude]: crate::prelude
375//!
04454e1e 376//! # Recording Traces
c295e0f8
XL
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//!
04454e1e 385//! # Filtering with `Layer`s
c295e0f8
XL
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//!
04454e1e 397//! ## Global Filtering
c295e0f8
XL
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//!
064997fb
FG
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` regesters 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//!
04454e1e 440//! ## Per-Layer Filtering
c295e0f8
XL
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//! <pre class="compile_fail" style="white-space:normal;font:inherit;">
472//! <strong>Warning</strong>: Currently, the <a href="../struct.Registry.html">
473//! <code>Registry</code></a> type defined in this crate is the only root
474//! <code>Subscriber</code> capable of supporting <code>Layer</code>s with
475//! per-layer filters. In the future, new APIs will be added to allow other
476//! root <code>Subscriber</code>s to support per-layer filters.
477//! </pre>
478//!
479//! For example, to generate an HTTP access log based on spans with
480//! the `http_access` target, while logging other spans and events to
481//! standard out, a [`Filter`] can be added to the access log layer:
482//!
483//! ```
484//! use tracing_subscriber::{filter, prelude::*};
485//!
486//! // Generates an HTTP access log.
487//! let access_log = // ...
488//! # filter::LevelFilter::INFO;
489//!
490//! // Add a filter to the access log layer so that it only observes
491//! // spans and events with the `http_access` target.
492//! let access_log = access_log.with_filter(filter::filter_fn(|metadata| {
493//! // Returns `true` if and only if the span or event's target is
494//! // "http_access".
495//! metadata.target() == "http_access"
496//! }));
497//!
498//! // A general-purpose logging layer.
499//! let fmt_layer = tracing_subscriber::fmt::layer();
500//!
501//! // Build a subscriber that combines the access log and stdout log
502//! // layers.
503//! tracing_subscriber::registry()
504//! .with(fmt_layer)
505//! .with(access_log)
506//! .init();
507//! ```
508//!
509//! Multiple layers can have their own, separate per-layer filters. A span or
510//! event will be recorded if it is enabled by _any_ per-layer filter, but it
511//! will be skipped by the layers whose filters did not enable it. Building on
512//! the previous example:
513//!
514//! ```
515//! use tracing_subscriber::{filter::{filter_fn, LevelFilter}, prelude::*};
516//!
517//! let access_log = // ...
518//! # LevelFilter::INFO;
519//! let fmt_layer = tracing_subscriber::fmt::layer();
520//!
521//! tracing_subscriber::registry()
522//! // Add the filter for the "http_access" target to the access
523//! // log layer, like before.
524//! .with(access_log.with_filter(filter_fn(|metadata| {
525//! metadata.target() == "http_access"
526//! })))
527//! // Add a filter for spans and events with the INFO level
528//! // and below to the logging layer.
529//! .with(fmt_layer.with_filter(LevelFilter::INFO))
530//! .init();
531//!
532//! // Neither layer will observe this event
533//! tracing::debug!(does_anyone_care = false, "a tree fell in the forest");
534//!
535//! // This event will be observed by the logging layer, but not
536//! // by the access log layer.
537//! tracing::warn!(dose_roentgen = %3.8, "not great, but not terrible");
538//!
539//! // This event will be observed only by the access log layer.
540//! tracing::trace!(target: "http_access", "HTTP request started");
541//!
542//! // Both layers will observe this event.
543//! tracing::error!(target: "http_access", "HTTP request failed with a very bad error!");
544//! ```
545//!
546//! A per-layer filter can be applied to multiple [`Layer`]s at a time, by
547//! combining them into a [`Layered`] layer using [`Layer::and_then`], and then
548//! calling [`Layer::with_filter`] on the resulting [`Layered`] layer.
549//!
550//! Consider the following:
551//! - `layer_a` and `layer_b`, which should only receive spans and events at
552//! the [`INFO`] [level] and above.
553//! - A third layer, `layer_c`, which should receive spans and events at
554//! the [`DEBUG`] [level] as well.
555//! The layers and filters would be composed thusly:
556//!
557//! ```
558//! use tracing_subscriber::{filter::LevelFilter, prelude::*};
559//!
560//! let layer_a = // ...
561//! # LevelFilter::INFO;
562//! let layer_b = // ...
563//! # LevelFilter::INFO;
564//! let layer_c = // ...
565//! # LevelFilter::INFO;
566//!
567//! let info_layers = layer_a
568//! // Combine `layer_a` and `layer_b` into a `Layered` layer:
569//! .and_then(layer_b)
570//! // ...and then add an `INFO` `LevelFilter` to that layer:
571//! .with_filter(LevelFilter::INFO);
572//!
573//! tracing_subscriber::registry()
574//! // Add `layer_c` with a `DEBUG` filter.
575//! .with(layer_c.with_filter(LevelFilter::DEBUG))
576//! .with(info_layers)
577//! .init();
578//!```
579//!
580//! If a [`Filtered`] [`Layer`] is combined with another [`Layer`]
581//! [`Layer::and_then`], and a filter is added to the [`Layered`] layer, that
582//! layer will be filtered by *both* the inner filter and the outer filter.
583//! Only spans and events that are enabled by *both* filters will be
584//! observed by that layer. This can be used to implement complex filtering
585//! trees.
586//!
587//! As an example, consider the following constraints:
588//! - Suppose that a particular [target] is used to indicate events that
589//! should be counted as part of a metrics system, which should be only
590//! observed by a layer that collects metrics.
591//! - A log of high-priority events ([`INFO`] and above) should be logged
592//! to stdout, while more verbose events should be logged to a debugging log file.
593//! - Metrics-focused events should *not* be included in either log output.
594//!
595//! In that case, it is possible to apply a filter to both logging layers to
596//! exclude the metrics events, while additionally adding a [`LevelFilter`]
597//! to the stdout log:
598//!
599//! ```
600//! # // wrap this in a function so we don't actually create `debug.log` when
601//! # // running the doctests..
602//! # fn docs() -> Result<(), Box<dyn std::error::Error + 'static>> {
603//! use tracing_subscriber::{filter, prelude::*};
604//! use std::{fs::File, sync::Arc};
605//!
606//! // A layer that logs events to stdout using the human-readable "pretty"
607//! // format.
608//! let stdout_log = tracing_subscriber::fmt::layer()
609//! .pretty();
610//!
611//! // A layer that logs events to a file.
612//! let file = File::create("debug.log")?;
613//! let debug_log = tracing_subscriber::fmt::layer()
614//! .with_writer(Arc::new(file));
615//!
616//! // A layer that collects metrics using specific events.
617//! let metrics_layer = /* ... */ filter::LevelFilter::INFO;
618//!
619//! tracing_subscriber::registry()
620//! .with(
621//! stdout_log
622//! // Add an `INFO` filter to the stdout logging layer
623//! .with_filter(filter::LevelFilter::INFO)
624//! // Combine the filtered `stdout_log` layer with the
625//! // `debug_log` layer, producing a new `Layered` layer.
626//! .and_then(debug_log)
627//! // Add a filter to *both* layers that rejects spans and
628//! // events whose targets start with `metrics`.
629//! .with_filter(filter::filter_fn(|metadata| {
630//! !metadata.target().starts_with("metrics")
631//! }))
632//! )
633//! .with(
634//! // Add a filter to the metrics label that *only* enables
635//! // events whose targets start with `metrics`.
636//! metrics_layer.with_filter(filter::filter_fn(|metadata| {
637//! metadata.target().starts_with("metrics")
638//! }))
639//! )
640//! .init();
641//!
642//! // This event will *only* be recorded by the metrics layer.
643//! tracing::info!(target: "metrics::cool_stuff_count", value = 42);
644//!
645//! // This event will only be seen by the debug log file layer:
646//! tracing::debug!("this is a message, and part of a system of messages");
647//!
648//! // This event will be seen by both the stdout log layer *and*
649//! // the debug log file layer, but not by the metrics layer.
650//! tracing::warn!("the message is a warning about danger!");
651//! # Ok(()) }
652//! ```
653//!
064997fb
FG
654//! [`Subscriber`]: tracing_core::subscriber::Subscriber
655//! [span IDs]: tracing_core::span::Id
c295e0f8
XL
656//! [the current span]: Context::current_span
657//! [`register_callsite`]: Layer::register_callsite
658//! [`enabled`]: Layer::enabled
064997fb 659//! [`event_enabled`]: Layer::event_enabled
c295e0f8
XL
660//! [`on_enter`]: Layer::on_enter
661//! [`Layer::register_callsite`]: Layer::register_callsite
662//! [`Layer::enabled`]: Layer::enabled
064997fb 663//! [`Interest::never()`]: tracing_core::subscriber::Interest::never()
c295e0f8
XL
664//! [`Filtered`]: crate::filter::Filtered
665//! [`filter`]: crate::filter
666//! [`Targets`]: crate::filter::Targets
667//! [`FilterFn`]: crate::filter::FilterFn
668//! [`DynFilterFn`]: crate::filter::DynFilterFn
669//! [level]: tracing_core::Level
670//! [`INFO`]: tracing_core::Level::INFO
671//! [`DEBUG`]: tracing_core::Level::DEBUG
672//! [target]: tracing_core::Metadata::target
673//! [`LevelFilter`]: crate::filter::LevelFilter
674//! [feat]: crate#feature-flags
675use crate::filter;
a2a8927a 676
c295e0f8
XL
677use tracing_core::{
678 metadata::Metadata,
679 span,
680 subscriber::{Interest, Subscriber},
681 Event, LevelFilter,
682};
683
a2a8927a
XL
684use core::any::TypeId;
685
686feature! {
687 #![feature = "alloc"]
688 use alloc::boxed::Box;
689 use core::ops::{Deref, DerefMut};
690}
691
c295e0f8
XL
692mod context;
693mod layered;
694pub use self::{context::*, layered::*};
695
696// The `tests` module is `pub(crate)` because it contains test utilities used by
697// other modules.
698#[cfg(test)]
699pub(crate) mod tests;
700
701/// A composable handler for `tracing` events.
702///
703/// A `Layer` implements a behavior for recording or collecting traces that can
704/// be composed together with other `Layer`s to build a [`Subscriber`]. See the
705/// [module-level documentation](crate::layer) for details.
706///
707/// [`Subscriber`]: tracing_core::Subscriber
708#[cfg_attr(docsrs, doc(notable_trait))]
709pub trait Layer<S>
710where
711 S: Subscriber,
712 Self: 'static,
713{
714 /// Performs late initialization when attaching a `Layer` to a
715 /// [`Subscriber`].
716 ///
717 /// This is a callback that is called when the `Layer` is added to a
718 /// [`Subscriber`] (e.g. in [`Layer::with_subscriber`] and
719 /// [`SubscriberExt::with`]). Since this can only occur before the
720 /// [`Subscriber`] has been set as the default, both the `Layer` and
721 /// [`Subscriber`] are passed to this method _mutably_. This gives the
722 /// `Layer` the opportunity to set any of its own fields with values
723 /// recieved by method calls on the [`Subscriber`].
724 ///
725 /// For example, [`Filtered`] layers implement `on_layer` to call the
726 /// [`Subscriber`]'s [`register_filter`] method, and store the returned
727 /// [`FilterId`] as a field.
728 ///
729 /// **Note** In most cases, `Layer` implementations will not need to
730 /// implement this method. However, in cases where a type implementing
731 /// `Layer` wraps one or more other types that implement `Layer`, like the
732 /// [`Layered`] and [`Filtered`] types in this crate, that type MUST ensure
733 /// that the inner `Layer`s' `on_layer` methods are called. Otherwise,
734 /// functionality that relies on `on_layer`, such as [per-layer filtering],
735 /// may not work correctly.
736 ///
737 /// [`Filtered`]: crate::filter::Filtered
738 /// [`register_filter`]: crate::registry::LookupSpan::register_filter
739 /// [per-layer filtering]: #per-layer-filtering
740 /// [`FilterId`]: crate::filter::FilterId
741 fn on_layer(&mut self, subscriber: &mut S) {
742 let _ = subscriber;
743 }
744
745 /// Registers a new callsite with this layer, returning whether or not
746 /// the layer is interested in being notified about the callsite, similarly
747 /// to [`Subscriber::register_callsite`].
748 ///
749 /// By default, this returns [`Interest::always()`] if [`self.enabled`] returns
750 /// true, or [`Interest::never()`] if it returns false.
751 ///
752 /// <pre class="ignore" style="white-space:normal;font:inherit;">
753 /// <strong>Note</strong>: This method (and <a href="#method.enabled">
754 /// <code>Layer::enabled</code></a>) determine whether a span or event is
755 /// globally enabled, <em>not</em> whether the individual layer will be
756 /// notified about that span or event. This is intended to be used
757 /// by layers that implement filtering for the entire stack. Layers which do
758 /// not wish to be notified about certain spans or events but do not wish to
759 /// globally disable them should ignore those spans or events in their
760 /// <a href="#method.on_event"><code>on_event</code></a>,
761 /// <a href="#method.on_enter"><code>on_enter</code></a>,
762 /// <a href="#method.on_exit"><code>on_exit</code></a>, and other notification
763 /// methods.
764 /// </pre>
765 ///
766 /// See [the trait-level documentation] for more information on filtering
767 /// with `Layer`s.
768 ///
769 /// Layers may also implement this method to perform any behaviour that
770 /// should be run once per callsite. If the layer wishes to use
771 /// `register_callsite` for per-callsite behaviour, but does not want to
772 /// globally enable or disable those callsites, it should always return
773 /// [`Interest::always()`].
774 ///
064997fb
FG
775 /// [`Interest`]: tracing_core::Interest
776 /// [`Subscriber::register_callsite`]: tracing_core::Subscriber::register_callsite()
777 /// [`Interest::never()`]: tracing_core::subscriber::Interest::never()
778 /// [`Interest::always()`]: tracing_core::subscriber::Interest::always()
779 /// [`self.enabled`]: Layer::enabled()
780 /// [`Layer::enabled`]: Layer::enabled()
781 /// [`on_event`]: Layer::on_event()
782 /// [`on_enter`]: Layer::on_enter()
783 /// [`on_exit`]: Layer::on_exit()
c295e0f8
XL
784 /// [the trait-level documentation]: #filtering-with-layers
785 fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
786 if self.enabled(metadata, Context::none()) {
787 Interest::always()
788 } else {
789 Interest::never()
790 }
791 }
792
793 /// Returns `true` if this layer is interested in a span or event with the
794 /// given `metadata` in the current [`Context`], similarly to
795 /// [`Subscriber::enabled`].
796 ///
797 /// By default, this always returns `true`, allowing the wrapped subscriber
798 /// to choose to disable the span.
799 ///
800 /// <pre class="ignore" style="white-space:normal;font:inherit;">
801 /// <strong>Note</strong>: This method (and <a href="#method.register_callsite">
802 /// <code>Layer::register_callsite</code></a>) determine whether a span or event is
803 /// globally enabled, <em>not</em> whether the individual layer will be
804 /// notified about that span or event. This is intended to be used
805 /// by layers that implement filtering for the entire stack. Layers which do
806 /// not wish to be notified about certain spans or events but do not wish to
807 /// globally disable them should ignore those spans or events in their
808 /// <a href="#method.on_event"><code>on_event</code></a>,
809 /// <a href="#method.on_enter"><code>on_enter</code></a>,
810 /// <a href="#method.on_exit"><code>on_exit</code></a>, and other notification
811 /// methods.
812 /// </pre>
813 ///
814 ///
815 /// See [the trait-level documentation] for more information on filtering
816 /// with `Layer`s.
817 ///
064997fb
FG
818 /// [`Interest`]: tracing_core::Interest
819 /// [`Subscriber::enabled`]: tracing_core::Subscriber::enabled()
820 /// [`Layer::register_callsite`]: Layer::register_callsite()
821 /// [`on_event`]: Layer::on_event()
822 /// [`on_enter`]: Layer::on_enter()
823 /// [`on_exit`]: Layer::on_exit()
c295e0f8
XL
824 /// [the trait-level documentation]: #filtering-with-layers
825 fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
826 let _ = (metadata, ctx);
827 true
828 }
829
830 /// Notifies this layer that a new span was constructed with the given
831 /// `Attributes` and `Id`.
a2a8927a 832 fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
c295e0f8
XL
833 let _ = (attrs, id, ctx);
834 }
835
836 // TODO(eliza): do we want this to be a public API? If we end up moving
837 // filtering layers to a separate trait, we may no longer want `Layer`s to
838 // be able to participate in max level hinting...
839 #[doc(hidden)]
840 fn max_level_hint(&self) -> Option<LevelFilter> {
841 None
842 }
843
844 /// Notifies this layer that a span with the given `Id` recorded the given
845 /// `values`.
846 // Note: it's unclear to me why we'd need the current span in `record` (the
847 // only thing the `Context` type currently provides), but passing it in anyway
848 // seems like a good future-proofing measure as it may grow other methods later...
849 fn on_record(&self, _span: &span::Id, _values: &span::Record<'_>, _ctx: Context<'_, S>) {}
850
851 /// Notifies this layer that a span with the ID `span` recorded that it
852 /// follows from the span with the ID `follows`.
853 // Note: it's unclear to me why we'd need the current span in `record` (the
854 // only thing the `Context` type currently provides), but passing it in anyway
855 // seems like a good future-proofing measure as it may grow other methods later...
856 fn on_follows_from(&self, _span: &span::Id, _follows: &span::Id, _ctx: Context<'_, S>) {}
857
064997fb
FG
858 /// Called before [`on_event`], to determine if `on_event` should be called.
859 ///
860 /// <div class="example-wrap" style="display:inline-block">
861 /// <pre class="ignore" style="white-space:normal;font:inherit;">
862 ///
863 /// **Note**: This method determines whether an event is globally enabled,
864 /// *not* whether the individual `Layer` will be notified about the
865 /// event. This is intended to be used by `Layer`s that implement
866 /// filtering for the entire stack. `Layer`s which do not wish to be
867 /// notified about certain events but do not wish to globally disable them
868 /// should ignore those events in their [on_event][Self::on_event].
869 ///
870 /// </pre></div>
871 ///
872 /// See [the trait-level documentation] for more information on filtering
873 /// with `Layer`s.
874 ///
875 /// [`on_event`]: Self::on_event
876 /// [`Interest`]: tracing_core::Interest
877 /// [the trait-level documentation]: #filtering-with-layers
878 #[inline] // collapse this to a constant please mrs optimizer
879 fn event_enabled(&self, _event: &Event<'_>, _ctx: Context<'_, S>) -> bool {
880 true
881 }
882
c295e0f8
XL
883 /// Notifies this layer that an event has occurred.
884 fn on_event(&self, _event: &Event<'_>, _ctx: Context<'_, S>) {}
885
886 /// Notifies this layer that a span with the given ID was entered.
887 fn on_enter(&self, _id: &span::Id, _ctx: Context<'_, S>) {}
888
889 /// Notifies this layer that the span with the given ID was exited.
890 fn on_exit(&self, _id: &span::Id, _ctx: Context<'_, S>) {}
891
892 /// Notifies this layer that the span with the given ID has been closed.
893 fn on_close(&self, _id: span::Id, _ctx: Context<'_, S>) {}
894
895 /// Notifies this layer that a span ID has been cloned, and that the
896 /// subscriber returned a different ID.
897 fn on_id_change(&self, _old: &span::Id, _new: &span::Id, _ctx: Context<'_, S>) {}
898
899 /// Composes this layer around the given `Layer`, returning a `Layered`
900 /// struct implementing `Layer`.
901 ///
902 /// The returned `Layer` will call the methods on this `Layer` and then
903 /// those of the new `Layer`, before calling the methods on the subscriber
904 /// it wraps. For example:
905 ///
906 /// ```rust
907 /// # use tracing_subscriber::layer::Layer;
908 /// # use tracing_core::Subscriber;
909 /// pub struct FooLayer {
910 /// // ...
911 /// }
912 ///
913 /// pub struct BarLayer {
914 /// // ...
915 /// }
916 ///
917 /// pub struct MySubscriber {
918 /// // ...
919 /// }
920 ///
921 /// impl<S: Subscriber> Layer<S> for FooLayer {
922 /// // ...
923 /// }
924 ///
925 /// impl<S: Subscriber> Layer<S> for BarLayer {
926 /// // ...
927 /// }
928 ///
929 /// # impl FooLayer {
930 /// # fn new() -> Self { Self {} }
931 /// # }
932 /// # impl BarLayer {
933 /// # fn new() -> Self { Self { }}
934 /// # }
935 /// # impl MySubscriber {
936 /// # fn new() -> Self { Self { }}
937 /// # }
938 /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
939 /// # impl tracing_core::Subscriber for MySubscriber {
940 /// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
941 /// # fn record(&self, _: &Id, _: &Record) {}
942 /// # fn event(&self, _: &Event) {}
943 /// # fn record_follows_from(&self, _: &Id, _: &Id) {}
944 /// # fn enabled(&self, _: &Metadata) -> bool { false }
945 /// # fn enter(&self, _: &Id) {}
946 /// # fn exit(&self, _: &Id) {}
947 /// # }
948 /// let subscriber = FooLayer::new()
949 /// .and_then(BarLayer::new())
950 /// .with_subscriber(MySubscriber::new());
951 /// ```
952 ///
953 /// Multiple layers may be composed in this manner:
954 ///
955 /// ```rust
956 /// # use tracing_subscriber::layer::Layer;
957 /// # use tracing_core::Subscriber;
958 /// # pub struct FooLayer {}
959 /// # pub struct BarLayer {}
960 /// # pub struct MySubscriber {}
961 /// # impl<S: Subscriber> Layer<S> for FooLayer {}
962 /// # impl<S: Subscriber> Layer<S> for BarLayer {}
963 /// # impl FooLayer {
964 /// # fn new() -> Self { Self {} }
965 /// # }
966 /// # impl BarLayer {
967 /// # fn new() -> Self { Self { }}
968 /// # }
969 /// # impl MySubscriber {
970 /// # fn new() -> Self { Self { }}
971 /// # }
972 /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
973 /// # impl tracing_core::Subscriber for MySubscriber {
974 /// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
975 /// # fn record(&self, _: &Id, _: &Record) {}
976 /// # fn event(&self, _: &Event) {}
977 /// # fn record_follows_from(&self, _: &Id, _: &Id) {}
978 /// # fn enabled(&self, _: &Metadata) -> bool { false }
979 /// # fn enter(&self, _: &Id) {}
980 /// # fn exit(&self, _: &Id) {}
981 /// # }
982 /// pub struct BazLayer {
983 /// // ...
984 /// }
985 ///
986 /// impl<S: Subscriber> Layer<S> for BazLayer {
987 /// // ...
988 /// }
989 /// # impl BazLayer { fn new() -> Self { BazLayer {} } }
990 ///
991 /// let subscriber = FooLayer::new()
992 /// .and_then(BarLayer::new())
993 /// .and_then(BazLayer::new())
994 /// .with_subscriber(MySubscriber::new());
995 /// ```
996 fn and_then<L>(self, layer: L) -> Layered<L, Self, S>
997 where
998 L: Layer<S>,
999 Self: Sized,
1000 {
1001 let inner_has_layer_filter = filter::layer_has_plf(&self);
1002 Layered::new(layer, self, inner_has_layer_filter)
1003 }
1004
1005 /// Composes this `Layer` with the given [`Subscriber`], returning a
1006 /// `Layered` struct that implements [`Subscriber`].
1007 ///
1008 /// The returned `Layered` subscriber will call the methods on this `Layer`
1009 /// and then those of the wrapped subscriber.
1010 ///
1011 /// For example:
1012 /// ```rust
1013 /// # use tracing_subscriber::layer::Layer;
1014 /// # use tracing_core::Subscriber;
1015 /// pub struct FooLayer {
1016 /// // ...
1017 /// }
1018 ///
1019 /// pub struct MySubscriber {
1020 /// // ...
1021 /// }
1022 ///
1023 /// impl<S: Subscriber> Layer<S> for FooLayer {
1024 /// // ...
1025 /// }
1026 ///
1027 /// # impl FooLayer {
1028 /// # fn new() -> Self { Self {} }
1029 /// # }
1030 /// # impl MySubscriber {
1031 /// # fn new() -> Self { Self { }}
1032 /// # }
1033 /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata};
1034 /// # impl tracing_core::Subscriber for MySubscriber {
1035 /// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
1036 /// # fn record(&self, _: &Id, _: &Record) {}
1037 /// # fn event(&self, _: &tracing_core::Event) {}
1038 /// # fn record_follows_from(&self, _: &Id, _: &Id) {}
1039 /// # fn enabled(&self, _: &Metadata) -> bool { false }
1040 /// # fn enter(&self, _: &Id) {}
1041 /// # fn exit(&self, _: &Id) {}
1042 /// # }
1043 /// let subscriber = FooLayer::new()
1044 /// .with_subscriber(MySubscriber::new());
1045 ///```
1046 ///
064997fb 1047 /// [`Subscriber`]: tracing_core::Subscriber
c295e0f8
XL
1048 fn with_subscriber(mut self, mut inner: S) -> Layered<Self, S>
1049 where
1050 Self: Sized,
1051 {
1052 let inner_has_layer_filter = filter::subscriber_has_plf(&inner);
1053 self.on_layer(&mut inner);
1054 Layered::new(self, inner, inner_has_layer_filter)
1055 }
1056
1057 /// Combines `self` with a [`Filter`], returning a [`Filtered`] layer.
1058 ///
1059 /// The [`Filter`] will control which spans and events are enabled for
1060 /// this layer. See [the trait-level documentation][plf] for details on
1061 /// per-layer filtering.
1062 ///
1063 /// [`Filtered`]: crate::filter::Filtered
5099ac24 1064 /// [plf]: crate::layer#per-layer-filtering
a2a8927a
XL
1065 #[cfg(all(feature = "registry", feature = "std"))]
1066 #[cfg_attr(docsrs, doc(cfg(all(feature = "registry", feature = "std"))))]
c295e0f8
XL
1067 fn with_filter<F>(self, filter: F) -> filter::Filtered<Self, F, S>
1068 where
1069 Self: Sized,
1070 F: Filter<S>,
1071 {
1072 filter::Filtered::new(self, filter)
1073 }
1074
04454e1e
FG
1075 /// Erases the type of this [`Layer`], returning a [`Box`]ed `dyn
1076 /// Layer` trait object.
1077 ///
1078 /// This can be used when a function returns a `Layer` which may be of
1079 /// one of several types, or when a `Layer` subscriber has a very long type
1080 /// signature.
1081 ///
1082 /// # Examples
1083 ///
1084 /// The following example will *not* compile, because the value assigned to
1085 /// `log_layer` may have one of several different types:
1086 ///
1087 /// ```compile_fail
1088 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1089 /// use tracing_subscriber::{Layer, filter::LevelFilter, prelude::*};
1090 /// use std::{path::PathBuf, fs::File, io};
1091 ///
1092 /// /// Configures whether logs are emitted to a file, to stdout, or to stderr.
1093 /// pub enum LogConfig {
1094 /// File(PathBuf),
1095 /// Stdout,
1096 /// Stderr,
1097 /// }
1098 ///
1099 /// let config = // ...
1100 /// # LogConfig::Stdout;
1101 ///
1102 /// // Depending on the config, construct a layer of one of several types.
1103 /// let log_layer = match config {
1104 /// // If logging to a file, use a maximally-verbose configuration.
1105 /// LogConfig::File(path) => {
1106 /// let file = File::create(path)?;
1107 /// tracing_subscriber::fmt::layer()
1108 /// .with_thread_ids(true)
1109 /// .with_thread_names(true)
1110 /// // Selecting the JSON logging format changes the layer's
1111 /// // type.
1112 /// .json()
1113 /// .with_span_list(true)
1114 /// // Setting the writer to use our log file changes the
1115 /// // layer's type again.
1116 /// .with_writer(file)
1117 /// },
1118 ///
1119 /// // If logging to stdout, use a pretty, human-readable configuration.
1120 /// LogConfig::Stdout => tracing_subscriber::fmt::layer()
1121 /// // Selecting the "pretty" logging format changes the
1122 /// // layer's type!
1123 /// .pretty()
1124 /// .with_writer(io::stdout)
1125 /// // Add a filter based on the RUST_LOG environment variable;
1126 /// // this changes the type too!
1127 /// .and_then(tracing_subscriber::EnvFilter::from_default_env()),
1128 ///
1129 /// // If logging to stdout, only log errors and warnings.
1130 /// LogConfig::Stderr => tracing_subscriber::fmt::layer()
1131 /// // Changing the writer changes the layer's type
1132 /// .with_writer(io::stderr)
1133 /// // Only log the `WARN` and `ERROR` levels. Adding a filter
1134 /// // changes the layer's type to `Filtered<LevelFilter, ...>`.
1135 /// .with_filter(LevelFilter::WARN),
1136 /// };
1137 ///
1138 /// tracing_subscriber::registry()
1139 /// .with(log_layer)
1140 /// .init();
1141 /// # Ok(()) }
1142 /// ```
1143 ///
1144 /// However, adding a call to `.boxed()` after each match arm erases the
1145 /// layer's type, so this code *does* compile:
1146 ///
1147 /// ```
1148 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1149 /// # use tracing_subscriber::{Layer, filter::LevelFilter, prelude::*};
1150 /// # use std::{path::PathBuf, fs::File, io};
1151 /// # pub enum LogConfig {
1152 /// # File(PathBuf),
1153 /// # Stdout,
1154 /// # Stderr,
1155 /// # }
1156 /// # let config = LogConfig::Stdout;
1157 /// let log_layer = match config {
1158 /// LogConfig::File(path) => {
1159 /// let file = File::create(path)?;
1160 /// tracing_subscriber::fmt::layer()
1161 /// .with_thread_ids(true)
1162 /// .with_thread_names(true)
1163 /// .json()
1164 /// .with_span_list(true)
1165 /// .with_writer(file)
1166 /// // Erase the type by boxing the layer
1167 /// .boxed()
1168 /// },
1169 ///
1170 /// LogConfig::Stdout => tracing_subscriber::fmt::layer()
1171 /// .pretty()
1172 /// .with_writer(io::stdout)
1173 /// .and_then(tracing_subscriber::EnvFilter::from_default_env())
1174 /// // Erase the type by boxing the layer
1175 /// .boxed(),
1176 ///
1177 /// LogConfig::Stderr => tracing_subscriber::fmt::layer()
1178 /// .with_writer(io::stderr)
1179 /// .with_filter(LevelFilter::WARN)
1180 /// // Erase the type by boxing the layer
1181 /// .boxed(),
1182 /// };
1183 ///
1184 /// tracing_subscriber::registry()
1185 /// .with(log_layer)
1186 /// .init();
1187 /// # Ok(()) }
1188 /// ```
1189 #[cfg(any(feature = "alloc", feature = "std"))]
1190 #[cfg_attr(docsrs, doc(cfg(any(feature = "alloc", feature = "std"))))]
1191 fn boxed(self) -> Box<dyn Layer<S> + Send + Sync + 'static>
1192 where
1193 Self: Sized,
1194 Self: Layer<S> + Send + Sync + 'static,
1195 S: Subscriber,
1196 {
1197 Box::new(self)
1198 }
1199
c295e0f8
XL
1200 #[doc(hidden)]
1201 unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1202 if id == TypeId::of::<Self>() {
1203 Some(self as *const _ as *const ())
1204 } else {
1205 None
1206 }
1207 }
1208}
1209
a2a8927a
XL
1210feature! {
1211 #![all(feature = "registry", feature = "std")]
04454e1e 1212
a2a8927a
XL
1213 /// A per-[`Layer`] filter that determines whether a span or event is enabled
1214 /// for an individual layer.
c295e0f8 1215 ///
a2a8927a 1216 /// See [the module-level documentation][plf] for details on using [`Filter`]s.
c295e0f8 1217 ///
a2a8927a
XL
1218 /// [plf]: crate::layer#per-layer-filtering
1219 #[cfg_attr(docsrs, doc(notable_trait))]
1220 pub trait Filter<S> {
1221 /// Returns `true` if this layer is interested in a span or event with the
1222 /// given [`Metadata`] in the current [`Context`], similarly to
1223 /// [`Subscriber::enabled`].
1224 ///
1225 /// If this returns `false`, the span or event will be disabled _for the
1226 /// wrapped [`Layer`]_. Unlike [`Layer::enabled`], the span or event will
1227 /// still be recorded if any _other_ layers choose to enable it. However,
1228 /// the layer [filtered] by this filter will skip recording that span or
1229 /// event.
1230 ///
1231 /// If all layers indicate that they do not wish to see this span or event,
1232 /// it will be disabled.
1233 ///
1234 /// [`metadata`]: tracing_core::Metadata
1235 /// [`Subscriber::enabled`]: tracing_core::Subscriber::enabled
1236 /// [filtered]: crate::filter::Filtered
1237 fn enabled(&self, meta: &Metadata<'_>, cx: &Context<'_, S>) -> bool;
c295e0f8 1238
a2a8927a
XL
1239 /// Returns an [`Interest`] indicating whether this layer will [always],
1240 /// [sometimes], or [never] be interested in the given [`Metadata`].
1241 ///
1242 /// When a given callsite will [always] or [never] be enabled, the results
1243 /// of evaluating the filter may be cached for improved performance.
1244 /// Therefore, if a filter is capable of determining that it will always or
1245 /// never enable a particular callsite, providing an implementation of this
1246 /// function is recommended.
1247 ///
1248 /// <pre class="ignore" style="white-space:normal;font:inherit;">
1249 /// <strong>Note</strong>: If a <code>Filter</code> will perform
1250 /// <em>dynamic filtering</em> that depends on the current context in which
1251 /// a span or event was observered (e.g. only enabling an event when it
1252 /// occurs within a particular span), it <strong>must</strong> return
1253 /// <code>Interest::sometimes()</code> from this method. If it returns
1254 /// <code>Interest::always()</code> or <code>Interest::never()</code>, the
1255 /// <code>enabled</code> method may not be called when a particular instance
1256 /// of that span or event is recorded.
1257 /// </pre>
1258 ///
1259 /// This method is broadly similar to [`Subscriber::register_callsite`];
1260 /// however, since the returned value represents only the interest of
1261 /// *this* layer, the resulting behavior is somewhat different.
1262 ///
1263 /// If a [`Subscriber`] returns [`Interest::always()`][always] or
1264 /// [`Interest::never()`][never] for a given [`Metadata`], its [`enabled`]
1265 /// method is then *guaranteed* to never be called for that callsite. On the
1266 /// other hand, when a `Filter` returns [`Interest::always()`][always] or
1267 /// [`Interest::never()`][never] for a callsite, _other_ [`Layer`]s may have
1268 /// differing interests in that callsite. If this is the case, the callsite
1269 /// will recieve [`Interest::sometimes()`][sometimes], and the [`enabled`]
1270 /// method will still be called for that callsite when it records a span or
1271 /// event.
1272 ///
1273 /// Returning [`Interest::always()`][always] or [`Interest::never()`][never] from
1274 /// `Filter::callsite_enabled` will permanently enable or disable a
1275 /// callsite (without requiring subsequent calls to [`enabled`]) if and only
1276 /// if the following is true:
1277 ///
1278 /// - all [`Layer`]s that comprise the subscriber include `Filter`s
1279 /// (this includes a tree of [`Layered`] layers that share the same
1280 /// `Filter`)
1281 /// - all those `Filter`s return the same [`Interest`].
1282 ///
1283 /// For example, if a [`Subscriber`] consists of two [`Filtered`] layers,
1284 /// and both of those layers return [`Interest::never()`][never], that
1285 /// callsite *will* never be enabled, and the [`enabled`] methods of those
1286 /// [`Filter`]s will not be called.
1287 ///
1288 /// ## Default Implementation
1289 ///
1290 /// The default implementation of this method assumes that the
1291 /// `Filter`'s [`enabled`] method _may_ perform dynamic filtering, and
1292 /// returns [`Interest::sometimes()`][sometimes], to ensure that [`enabled`]
1293 /// is called to determine whether a particular _instance_ of the callsite
1294 /// is enabled in the current context. If this is *not* the case, and the
1295 /// `Filter`'s [`enabled`] method will always return the same result
1296 /// for a particular [`Metadata`], this method can be overridden as
1297 /// follows:
1298 ///
1299 /// ```
1300 /// use tracing_subscriber::layer;
1301 /// use tracing_core::{Metadata, subscriber::Interest};
1302 ///
1303 /// struct MyFilter {
1304 /// // ...
1305 /// }
1306 ///
1307 /// impl MyFilter {
1308 /// // The actual logic for determining whether a `Metadata` is enabled
1309 /// // must be factored out from the `enabled` method, so that it can be
1310 /// // called without a `Context` (which is not provided to the
1311 /// // `callsite_enabled` method).
1312 /// fn is_enabled(&self, metadata: &Metadata<'_>) -> bool {
1313 /// // ...
1314 /// # drop(metadata); true
1315 /// }
1316 /// }
1317 ///
1318 /// impl<S> layer::Filter<S> for MyFilter {
1319 /// fn enabled(&self, metadata: &Metadata<'_>, _: &layer::Context<'_, S>) -> bool {
1320 /// // Even though we are implementing `callsite_enabled`, we must still provide a
1321 /// // working implementation of `enabled`, as returning `Interest::always()` or
1322 /// // `Interest::never()` will *allow* caching, but will not *guarantee* it.
1323 /// // Other filters may still return `Interest::sometimes()`, so we may be
1324 /// // asked again in `enabled`.
1325 /// self.is_enabled(metadata)
1326 /// }
1327 ///
1328 /// fn callsite_enabled(&self, metadata: &'static Metadata<'static>) -> Interest {
1329 /// // The result of `self.enabled(metadata, ...)` will always be
1330 /// // the same for any given `Metadata`, so we can convert it into
1331 /// // an `Interest`:
1332 /// if self.is_enabled(metadata) {
1333 /// Interest::always()
1334 /// } else {
1335 /// Interest::never()
1336 /// }
1337 /// }
1338 /// }
1339 /// ```
1340 ///
1341 /// [`Metadata`]: tracing_core::Metadata
1342 /// [`Interest`]: tracing_core::Interest
1343 /// [always]: tracing_core::Interest::always
1344 /// [sometimes]: tracing_core::Interest::sometimes
1345 /// [never]: tracing_core::Interest::never
1346 /// [`Subscriber::register_callsite`]: tracing_core::Subscriber::register_callsite
1347 /// [`Subscriber`]: tracing_core::Subscriber
1348 /// [`enabled`]: Filter::enabled
1349 /// [`Filtered`]: crate::filter::Filtered
1350 fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
1351 let _ = meta;
1352 Interest::sometimes()
1353 }
c295e0f8 1354
a2a8927a
XL
1355 /// Returns an optional hint of the highest [verbosity level][level] that
1356 /// this `Filter` will enable.
1357 ///
1358 /// If this method returns a [`LevelFilter`], it will be used as a hint to
1359 /// determine the most verbose level that will be enabled. This will allow
1360 /// spans and events which are more verbose than that level to be skipped
1361 /// more efficiently. An implementation of this method is optional, but
1362 /// strongly encouraged.
1363 ///
1364 /// If the maximum level the `Filter` will enable can change over the
1365 /// course of its lifetime, it is free to return a different value from
1366 /// multiple invocations of this method. However, note that changes in the
1367 /// maximum level will **only** be reflected after the callsite [`Interest`]
1368 /// cache is rebuilt, by calling the
1369 /// [`tracing_core::callsite::rebuild_interest_cache`][rebuild] function.
1370 /// Therefore, if the `Filter will change the value returned by this
1371 /// method, it is responsible for ensuring that
1372 /// [`rebuild_interest_cache`][rebuild] is called after the value of the max
1373 /// level changes.
1374 ///
1375 /// ## Default Implementation
1376 ///
1377 /// By default, this method returns `None`, indicating that the maximum
1378 /// level is unknown.
1379 ///
1380 /// [level]: tracing_core::metadata::Level
1381 /// [`LevelFilter`]: crate::filter::LevelFilter
1382 /// [`Interest`]: tracing_core::subscriber::Interest
1383 /// [rebuild]: tracing_core::callsite::rebuild_interest_cache
1384 fn max_level_hint(&self) -> Option<LevelFilter> {
1385 None
1386 }
04454e1e
FG
1387
1388 /// Notifies this filter that a new span was constructed with the given
1389 /// `Attributes` and `Id`.
1390 ///
1391 /// By default, this method does nothing. `Filter` implementations that
1392 /// need to be notified when new spans are created can override this
1393 /// method.
1394 fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1395 let _ = (attrs, id, ctx);
1396 }
1397
1398
1399 /// Notifies this filter that a span with the given `Id` recorded the given
1400 /// `values`.
1401 ///
1402 /// By default, this method does nothing. `Filter` implementations that
1403 /// need to be notified when new spans are created can override this
1404 /// method.
1405 fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1406 let _ = (id, values, ctx);
1407 }
1408
1409 /// Notifies this filter that a span with the given ID was entered.
1410 ///
1411 /// By default, this method does nothing. `Filter` implementations that
1412 /// need to be notified when a span is entered can override this method.
1413 fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1414 let _ = (id, ctx);
1415 }
1416
1417 /// Notifies this filter that a span with the given ID was exited.
1418 ///
1419 /// By default, this method does nothing. `Filter` implementations that
1420 /// need to be notified when a span is exited can override this method.
1421 fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1422 let _ = (id, ctx);
1423 }
1424
1425 /// Notifies this filter that a span with the given ID has been closed.
1426 ///
1427 /// By default, this method does nothing. `Filter` implementations that
1428 /// need to be notified when a span is closed can override this method.
1429 fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1430 let _ = (id, ctx);
1431 }
c295e0f8
XL
1432 }
1433}
1434
1435/// Extension trait adding a `with(Layer)` combinator to `Subscriber`s.
1436pub trait SubscriberExt: Subscriber + crate::sealed::Sealed {
1437 /// Wraps `self` with the provided `layer`.
1438 fn with<L>(self, layer: L) -> Layered<L, Self>
1439 where
1440 L: Layer<Self>,
1441 Self: Sized,
1442 {
1443 layer.with_subscriber(self)
1444 }
1445}
a2a8927a 1446
c295e0f8
XL
1447/// A layer that does nothing.
1448#[derive(Clone, Debug, Default)]
1449pub struct Identity {
1450 _p: (),
1451}
1452
1453// === impl Layer ===
1454
1455impl<L, S> Layer<S> for Option<L>
1456where
1457 L: Layer<S>,
1458 S: Subscriber,
1459{
1460 fn on_layer(&mut self, subscriber: &mut S) {
1461 if let Some(ref mut layer) = self {
1462 layer.on_layer(subscriber)
1463 }
1464 }
1465
1466 #[inline]
a2a8927a 1467 fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
c295e0f8 1468 if let Some(ref inner) = self {
a2a8927a 1469 inner.on_new_span(attrs, id, ctx)
c295e0f8
XL
1470 }
1471 }
1472
1473 #[inline]
1474 fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
1475 match self {
1476 Some(ref inner) => inner.register_callsite(metadata),
1477 None => Interest::always(),
1478 }
1479 }
1480
1481 #[inline]
1482 fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
1483 match self {
1484 Some(ref inner) => inner.enabled(metadata, ctx),
1485 None => true,
1486 }
1487 }
1488
1489 #[inline]
1490 fn max_level_hint(&self) -> Option<LevelFilter> {
1491 match self {
1492 Some(ref inner) => inner.max_level_hint(),
064997fb
FG
1493 None => {
1494 // There is no inner layer, so this layer will
1495 // never enable anything.
1496 Some(LevelFilter::OFF)
1497 }
c295e0f8
XL
1498 }
1499 }
1500
1501 #[inline]
1502 fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1503 if let Some(ref inner) = self {
1504 inner.on_record(span, values, ctx);
1505 }
1506 }
1507
1508 #[inline]
1509 fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
1510 if let Some(ref inner) = self {
1511 inner.on_follows_from(span, follows, ctx);
1512 }
1513 }
1514
064997fb
FG
1515 #[inline]
1516 fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
1517 match self {
1518 Some(ref inner) => inner.event_enabled(event, ctx),
1519 None => true,
1520 }
1521 }
1522
c295e0f8
XL
1523 #[inline]
1524 fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
1525 if let Some(ref inner) = self {
1526 inner.on_event(event, ctx);
1527 }
1528 }
1529
1530 #[inline]
1531 fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1532 if let Some(ref inner) = self {
1533 inner.on_enter(id, ctx);
1534 }
1535 }
1536
1537 #[inline]
1538 fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1539 if let Some(ref inner) = self {
1540 inner.on_exit(id, ctx);
1541 }
1542 }
1543
1544 #[inline]
1545 fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1546 if let Some(ref inner) = self {
1547 inner.on_close(id, ctx);
1548 }
1549 }
1550
1551 #[inline]
1552 fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
1553 if let Some(ref inner) = self {
1554 inner.on_id_change(old, new, ctx)
1555 }
1556 }
1557
1558 #[doc(hidden)]
1559 #[inline]
1560 unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1561 if id == TypeId::of::<Self>() {
1562 Some(self as *const _ as *const ())
1563 } else {
1564 self.as_ref().and_then(|inner| inner.downcast_raw(id))
1565 }
1566 }
1567}
1568
a2a8927a
XL
1569feature! {
1570 #![any(feature = "std", feature = "alloc")]
04454e1e
FG
1571 #[cfg(not(feature = "std"))]
1572 use alloc::vec::Vec;
c295e0f8 1573
a2a8927a
XL
1574 macro_rules! layer_impl_body {
1575 () => {
1576 #[inline]
1577 fn on_layer(&mut self, subscriber: &mut S) {
1578 self.deref_mut().on_layer(subscriber);
1579 }
c295e0f8 1580
a2a8927a
XL
1581 #[inline]
1582 fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1583 self.deref().on_new_span(attrs, id, ctx)
1584 }
c295e0f8 1585
a2a8927a
XL
1586 #[inline]
1587 fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
1588 self.deref().register_callsite(metadata)
1589 }
c295e0f8 1590
a2a8927a
XL
1591 #[inline]
1592 fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
1593 self.deref().enabled(metadata, ctx)
1594 }
c295e0f8 1595
a2a8927a
XL
1596 #[inline]
1597 fn max_level_hint(&self) -> Option<LevelFilter> {
1598 self.deref().max_level_hint()
1599 }
c295e0f8 1600
a2a8927a
XL
1601 #[inline]
1602 fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1603 self.deref().on_record(span, values, ctx)
1604 }
c295e0f8 1605
a2a8927a
XL
1606 #[inline]
1607 fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
1608 self.deref().on_follows_from(span, follows, ctx)
1609 }
c295e0f8 1610
064997fb
FG
1611 #[inline]
1612 fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
1613 self.deref().event_enabled(event, ctx)
1614 }
1615
a2a8927a
XL
1616 #[inline]
1617 fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
1618 self.deref().on_event(event, ctx)
1619 }
c295e0f8 1620
a2a8927a
XL
1621 #[inline]
1622 fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1623 self.deref().on_enter(id, ctx)
1624 }
c295e0f8 1625
a2a8927a
XL
1626 #[inline]
1627 fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1628 self.deref().on_exit(id, ctx)
1629 }
c295e0f8 1630
a2a8927a
XL
1631 #[inline]
1632 fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1633 self.deref().on_close(id, ctx)
1634 }
c295e0f8 1635
a2a8927a
XL
1636 #[inline]
1637 fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
1638 self.deref().on_id_change(old, new, ctx)
1639 }
c295e0f8 1640
a2a8927a
XL
1641 #[doc(hidden)]
1642 #[inline]
1643 unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1644 self.deref().downcast_raw(id)
1645 }
1646 };
c295e0f8
XL
1647 }
1648
a2a8927a
XL
1649 impl<L, S> Layer<S> for Box<L>
1650 where
1651 L: Layer<S>,
1652 S: Subscriber,
1653 {
1654 layer_impl_body! {}
c295e0f8
XL
1655 }
1656
a2a8927a
XL
1657 impl<S> Layer<S> for Box<dyn Layer<S> + Send + Sync>
1658 where
1659 S: Subscriber,
1660 {
1661 layer_impl_body! {}
c295e0f8 1662 }
04454e1e
FG
1663
1664
1665
1666 impl<S, L> Layer<S> for Vec<L>
1667 where
1668 L: Layer<S>,
1669 S: Subscriber,
1670 {
1671
1672 fn on_layer(&mut self, subscriber: &mut S) {
1673 for l in self {
1674 l.on_layer(subscriber);
1675 }
1676 }
1677
1678 fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
1679 // Return highest level of interest.
1680 let mut interest = Interest::never();
1681 for l in self {
1682 let new_interest = l.register_callsite(metadata);
1683 if (interest.is_sometimes() && new_interest.is_always())
1684 || (interest.is_never() && !new_interest.is_never())
1685 {
1686 interest = new_interest;
1687 }
1688 }
1689
1690 interest
1691 }
1692
1693 fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
1694 self.iter().all(|l| l.enabled(metadata, ctx.clone()))
1695 }
1696
064997fb
FG
1697 fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
1698 self.iter().all(|l| l.event_enabled(event, ctx.clone()))
1699 }
1700
04454e1e
FG
1701 fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
1702 for l in self {
1703 l.on_new_span(attrs, id, ctx.clone());
1704 }
1705 }
1706
1707 fn max_level_hint(&self) -> Option<LevelFilter> {
064997fb
FG
1708 // Default to `OFF` if there are no inner layers.
1709 let mut max_level = LevelFilter::OFF;
04454e1e
FG
1710 for l in self {
1711 // NOTE(eliza): this is slightly subtle: if *any* layer
1712 // returns `None`, we have to return `None`, assuming there is
1713 // no max level hint, since that particular layer cannot
1714 // provide a hint.
1715 let hint = l.max_level_hint()?;
1716 max_level = core::cmp::max(hint, max_level);
1717 }
1718 Some(max_level)
1719 }
1720
1721 fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
1722 for l in self {
1723 l.on_record(span, values, ctx.clone())
1724 }
1725 }
1726
1727 fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
1728 for l in self {
1729 l.on_follows_from(span, follows, ctx.clone());
1730 }
1731 }
1732
1733 fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
1734 for l in self {
1735 l.on_event(event, ctx.clone());
1736 }
1737 }
1738
1739 fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
1740 for l in self {
1741 l.on_enter(id, ctx.clone());
1742 }
1743 }
1744
1745 fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
1746 for l in self {
1747 l.on_exit(id, ctx.clone());
1748 }
1749 }
1750
1751 fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
1752 for l in self {
1753 l.on_close(id.clone(), ctx.clone());
1754 }
1755 }
1756
1757 #[doc(hidden)]
1758 unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
1759 // If downcasting to `Self`, return a pointer to `self`.
1760 if id == TypeId::of::<Self>() {
1761 return Some(self as *const _ as *const ());
1762 }
1763
1764 // Someone is looking for per-layer filters. But, this `Vec`
1765 // might contain layers with per-layer filters *and*
1766 // layers without filters. It should only be treated as a
1767 // per-layer-filtered layer if *all* its layers have
1768 // per-layer filters.
1769 // XXX(eliza): it's a bummer we have to do this linear search every
1770 // time. It would be nice if this could be cached, but that would
1771 // require replacing the `Vec` impl with an impl for a newtype...
1772 if filter::is_plf_downcast_marker(id) && self.iter().any(|s| s.downcast_raw(id).is_none()) {
1773 return None;
1774 }
1775
1776 // Otherwise, return the first child of `self` that downcaasts to
1777 // the selected type, if any.
1778 // XXX(eliza): hope this is reasonable lol
1779 self.iter().find_map(|l| l.downcast_raw(id))
1780 }
1781 }
c295e0f8
XL
1782}
1783
1784// === impl SubscriberExt ===
1785
1786impl<S: Subscriber> crate::sealed::Sealed for S {}
1787impl<S: Subscriber> SubscriberExt for S {}
1788
1789// === impl Identity ===
1790
1791impl<S: Subscriber> Layer<S> for Identity {}
1792
1793impl Identity {
1794 /// Returns a new `Identity` layer.
1795 pub fn new() -> Self {
1796 Self { _p: () }
1797 }
1798}