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