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