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