tracing_subscriber/filter/layer_filters/
mod.rs

1//! ## Per-Layer Filtering
2//!
3//! Per-layer filters permit individual `Layer`s to have their own filter
4//! configurations without interfering with other `Layer`s.
5//!
6//! This module is not public; the public APIs defined in this module are
7//! re-exported in the top-level `filter` module. Therefore, this documentation
8//! primarily concerns the internal implementation details. For the user-facing
9//! public API documentation, see the individual public types in this module, as
10//! well as the, see the `Layer` trait documentation's [per-layer filtering
11//! section]][1].
12//!
13//! ## How does per-layer filtering work?
14//!
15//! As described in the API documentation, the [`Filter`] trait defines a
16//! filtering strategy for a per-layer filter. We expect there will be a variety
17//! of implementations of [`Filter`], both in `tracing-subscriber` and in user
18//! code.
19//!
20//! To actually *use* a [`Filter`] implementation, it is combined with a
21//! [`Layer`] by the [`Filtered`] struct defined in this module. [`Filtered`]
22//! implements [`Layer`] by calling into the wrapped [`Layer`], or not, based on
23//! the filtering strategy. While there will be a variety of types that implement
24//! [`Filter`], all actual *uses* of per-layer filtering will occur through the
25//! [`Filtered`] struct. Therefore, most of the implementation details live
26//! there.
27//!
28//! [1]: crate::layer#per-layer-filtering
29//! [`Filter`]: crate::layer::Filter
30use crate::{
31    filter::LevelFilter,
32    layer::{self, Context, Layer},
33    registry,
34};
35use alloc::{boxed::Box, fmt, sync::Arc};
36use core::{
37    any::TypeId,
38    cell::{Cell, RefCell},
39    marker::PhantomData,
40    ops::Deref,
41};
42use std::thread_local;
43use tracing_core::{
44    span,
45    subscriber::{Interest, Subscriber},
46    Dispatch, Event, Metadata,
47};
48pub mod combinator;
49
50/// A [`Layer`] that wraps an inner [`Layer`] and adds a [`Filter`] which
51/// controls what spans and events are enabled for that layer.
52///
53/// This is returned by the [`Layer::with_filter`] method. See the
54/// [documentation on per-layer filtering][plf] for details.
55///
56/// [`Filter`]: crate::layer::Filter
57/// [plf]: crate::layer#per-layer-filtering
58#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
59#[derive(Clone)]
60pub struct Filtered<L, F, S> {
61    filter: F,
62    layer: L,
63    id: MagicPlfDowncastMarker,
64    _s: PhantomData<fn(S)>,
65}
66
67/// Uniquely identifies an individual [`Filter`] instance in the context of
68/// a [`Subscriber`].
69///
70/// When adding a [`Filtered`] [`Layer`] to a [`Subscriber`], the [`Subscriber`]
71/// generates a `FilterId` for that [`Filtered`] layer. The [`Filtered`] layer
72/// will then use the generated ID to query whether a particular span was
73/// previously enabled by that layer's [`Filter`].
74///
75/// **Note**: Currently, the [`Registry`] type provided by this crate is the
76/// **only** [`Subscriber`] implementation capable of participating in per-layer
77/// filtering. Therefore, the `FilterId` type cannot currently be constructed by
78/// code outside of `tracing-subscriber`. In the future, new APIs will be added to `tracing-subscriber` to
79/// allow non-Registry [`Subscriber`]s to also participate in per-layer
80/// filtering. When those APIs are added, subscribers will be responsible
81/// for generating and assigning `FilterId`s.
82///
83/// [`Filter`]: crate::layer::Filter
84/// [`Subscriber`]: tracing_core::Subscriber
85/// [`Layer`]: crate::layer::Layer
86/// [`Registry`]: crate::registry::Registry
87#[cfg(feature = "registry")]
88#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
89#[derive(Copy, Clone)]
90pub struct FilterId(u64);
91
92/// A bitmap tracking which [`FilterId`]s have enabled a given span or
93/// event.
94///
95/// This is currently a private type that's used exclusively by the
96/// [`Registry`]. However, in the future, this may become a public API, in order
97/// to allow user subscribers to host [`Filter`]s.
98///
99/// [`Registry`]: crate::Registry
100/// [`Filter`]: crate::layer::Filter
101#[derive(Copy, Clone, Eq, PartialEq)]
102pub(crate) struct FilterMap {
103    bits: u64,
104}
105
106impl FilterMap {
107    pub(crate) const fn new() -> Self {
108        Self { bits: 0 }
109    }
110}
111
112/// The current state of `enabled` calls to per-subscriber filters on this
113/// thread.
114///
115/// When `Filtered::enabled` is called, the filter will set the bit
116/// corresponding to its ID if the filter will disable the event/span being
117/// filtered. When the event or span is recorded, the per-layer filter will
118/// check its bit to determine if it disabled that event or span, and skip
119/// forwarding the event or span to the inner layer if the bit is set. Once
120/// a span or event has been skipped by a per-layer filter, it unsets its
121/// bit, so that the `FilterMap` has been cleared for the next set of
122/// `enabled` calls.
123///
124/// FilterState is also read by the `Registry`, for two reasons:
125///
126/// 1. When filtering a span, the Registry must store the `FilterMap`
127///    generated by `Filtered::enabled` calls for that span as part of the
128///    span's per-span data. This allows `Filtered` layers to determine
129///    whether they had previously disabled a given span, and avoid showing it
130///    to the wrapped layer if it was disabled.
131///
132///    This allows `Filtered` layers to also filter out the spans they
133///    disable from span traversals (such as iterating over parents, etc).
134/// 2. If all the bits are set, then every per-layer filter has decided it
135///    doesn't want to enable that span or event. In that case, the
136///    `Registry`'s `enabled` method will return `false`, so that
137///    recording a span or event can be skipped entirely.
138#[derive(Debug)]
139pub(crate) struct FilterState {
140    enabled: Cell<FilterMap>,
141    // TODO(eliza): `Interest`s should _probably_ be `Copy`. The only reason
142    // they're not is our Obsessive Commitment to Forwards-Compatibility. If
143    // this changes in tracing-core`, we can make this a `Cell` rather than
144    // `RefCell`...
145    interest: RefCell<Option<Interest>>,
146
147    #[cfg(debug_assertions)]
148    counters: DebugCounters,
149}
150
151/// Extra counters added to `FilterState` used only to make debug assertions.
152#[cfg(debug_assertions)]
153#[derive(Debug)]
154struct DebugCounters {
155    /// How many per-layer filters have participated in the current `enabled`
156    /// call?
157    in_filter_pass: Cell<usize>,
158
159    /// How many per-layer filters have participated in the current `register_callsite`
160    /// call?
161    in_interest_pass: Cell<usize>,
162}
163
164#[cfg(debug_assertions)]
165impl DebugCounters {
166    const fn new() -> Self {
167        Self {
168            in_filter_pass: Cell::new(0),
169            in_interest_pass: Cell::new(0),
170        }
171    }
172}
173
174thread_local! {
175    pub(crate) static FILTERING: FilterState = const { FilterState::new() };
176}
177
178/// Extension trait adding [combinators] for combining [`Filter`].
179///
180/// [combinators]: crate::filter::combinator
181/// [`Filter`]: crate::layer::Filter
182pub trait FilterExt<S>: layer::Filter<S> {
183    /// Combines this [`Filter`] with another [`Filter`] s so that spans and
184    /// events are enabled if and only if *both* filters return `true`.
185    ///
186    /// # Examples
187    ///
188    /// Enabling spans or events if they have both a particular target *and* are
189    /// above a certain level:
190    ///
191    /// ```
192    /// use tracing_subscriber::{
193    ///     filter::{filter_fn, LevelFilter, FilterExt},
194    ///     prelude::*,
195    /// };
196    ///
197    /// // Enables spans and events with targets starting with `interesting_target`:
198    /// let target_filter = filter_fn(|meta| {
199    ///     meta.target().starts_with("interesting_target")
200    /// });
201    ///
202    /// // Enables spans and events with levels `INFO` and below:
203    /// let level_filter = LevelFilter::INFO;
204    ///
205    /// // Combine the two filters together, returning a filter that only enables
206    /// // spans and events that *both* filters will enable:
207    /// let filter = target_filter.and(level_filter);
208    ///
209    /// tracing_subscriber::registry()
210    ///     .with(tracing_subscriber::fmt::layer().with_filter(filter))
211    ///     .init();
212    ///
213    /// // This event will *not* be enabled:
214    /// tracing::info!("an event with an uninteresting target");
215    ///
216    /// // This event *will* be enabled:
217    /// tracing::info!(target: "interesting_target", "a very interesting event");
218    ///
219    /// // This event will *not* be enabled:
220    /// tracing::debug!(target: "interesting_target", "interesting debug event...");
221    /// ```
222    ///
223    /// [`Filter`]: crate::layer::Filter
224    fn and<B>(self, other: B) -> combinator::And<Self, B, S>
225    where
226        Self: Sized,
227        B: layer::Filter<S>,
228    {
229        combinator::And::new(self, other)
230    }
231
232    /// Combines two [`Filter`]s so that spans and events are enabled if *either* filter
233    /// returns `true`.
234    ///
235    /// # Examples
236    ///
237    /// Enabling spans and events at the `INFO` level and above, and all spans
238    /// and events with a particular target:
239    /// ```
240    /// use tracing_subscriber::{
241    ///     filter::{filter_fn, LevelFilter, FilterExt},
242    ///     prelude::*,
243    /// };
244    ///
245    /// // Enables spans and events with targets starting with `interesting_target`:
246    /// let target_filter = filter_fn(|meta| {
247    ///     meta.target().starts_with("interesting_target")
248    /// });
249    ///
250    /// // Enables spans and events with levels `INFO` and below:
251    /// let level_filter = LevelFilter::INFO;
252    ///
253    /// // Combine the two filters together so that a span or event is enabled
254    /// // if it is at INFO or lower, or if it has a target starting with
255    /// // `interesting_target`.
256    /// let filter = level_filter.or(target_filter);
257    ///
258    /// tracing_subscriber::registry()
259    ///     .with(tracing_subscriber::fmt::layer().with_filter(filter))
260    ///     .init();
261    ///
262    /// // This event will *not* be enabled:
263    /// tracing::debug!("an uninteresting event");
264    ///
265    /// // This event *will* be enabled:
266    /// tracing::info!("an uninteresting INFO event");
267    ///
268    /// // This event *will* be enabled:
269    /// tracing::info!(target: "interesting_target", "a very interesting event");
270    ///
271    /// // This event *will* be enabled:
272    /// tracing::debug!(target: "interesting_target", "interesting debug event...");
273    /// ```
274    ///
275    /// Enabling a higher level for a particular target by using `or` in
276    /// conjunction with the [`and`] combinator:
277    ///
278    /// ```
279    /// use tracing_subscriber::{
280    ///     filter::{filter_fn, LevelFilter, FilterExt},
281    ///     prelude::*,
282    /// };
283    ///
284    /// // This filter will enable spans and events with targets beginning with
285    /// // `my_crate`:
286    /// let my_crate = filter_fn(|meta| {
287    ///     meta.target().starts_with("my_crate")
288    /// });
289    ///
290    /// let filter = my_crate
291    ///     // Combine the `my_crate` filter with a `LevelFilter` to produce a
292    ///     // filter that will enable the `INFO` level and lower for spans and
293    ///     // events with `my_crate` targets:
294    ///     .and(LevelFilter::INFO)
295    ///     // If a span or event *doesn't* have a target beginning with
296    ///     // `my_crate`, enable it if it has the `WARN` level or lower:
297    ///     .or(LevelFilter::WARN);
298    ///
299    /// tracing_subscriber::registry()
300    ///     .with(tracing_subscriber::fmt::layer().with_filter(filter))
301    ///     .init();
302    /// ```
303    ///
304    /// [`Filter`]: crate::layer::Filter
305    /// [`and`]: FilterExt::and
306    fn or<B>(self, other: B) -> combinator::Or<Self, B, S>
307    where
308        Self: Sized,
309        B: layer::Filter<S>,
310    {
311        combinator::Or::new(self, other)
312    }
313
314    /// Inverts `self`, returning a filter that enables spans and events only if
315    /// `self` would *not* enable them.
316    ///
317    /// This inverts the values returned by the [`enabled`] and [`callsite_enabled`]
318    /// methods on the wrapped filter; it does *not* invert [`event_enabled`], as
319    /// filters which do not implement filtering on event field values will return
320    /// the default `true` even for events that their [`enabled`] method disables.
321    ///
322    /// Consider a normal filter defined as:
323    ///
324    /// ```ignore (pseudo-code)
325    /// // for spans
326    /// match callsite_enabled() {
327    ///     ALWAYS => on_span(),
328    ///     SOMETIMES => if enabled() { on_span() },
329    ///     NEVER => (),
330    /// }
331    /// // for events
332    /// match callsite_enabled() {
333    ///    ALWAYS => on_event(),
334    ///    SOMETIMES => if enabled() && event_enabled() { on_event() },
335    ///    NEVER => (),
336    /// }
337    /// ```
338    ///
339    /// and an inverted filter defined as:
340    ///
341    /// ```ignore (pseudo-code)
342    /// // for spans
343    /// match callsite_enabled() {
344    ///     ALWAYS => (),
345    ///     SOMETIMES => if !enabled() { on_span() },
346    ///     NEVER => on_span(),
347    /// }
348    /// // for events
349    /// match callsite_enabled() {
350    ///     ALWAYS => (),
351    ///     SOMETIMES => if !enabled() { on_event() },
352    ///     NEVER => on_event(),
353    /// }
354    /// ```
355    ///
356    /// A proper inversion would do `!(enabled() && event_enabled())` (or
357    /// `!enabled() || !event_enabled()`), but because of the implicit `&&`
358    /// relation between `enabled` and `event_enabled`, it is difficult to
359    /// short circuit and not call the wrapped `event_enabled`.
360    ///
361    /// A combinator which remembers the result of `enabled` in order to call
362    /// `event_enabled` only when `enabled() == true` is possible, but requires
363    /// additional thread-local mutable state to support a very niche use case.
364    //
365    //  Also, it'd mean the wrapped layer's `enabled()` always gets called and
366    //  globally applied to events where it doesn't today, since we can't know
367    //  what `event_enabled` will say until we have the event to call it with.
368    ///
369    /// [`Filter`]: crate::layer::Filter
370    /// [`enabled`]: crate::layer::Filter::enabled
371    /// [`event_enabled`]: crate::layer::Filter::event_enabled
372    /// [`callsite_enabled`]: crate::layer::Filter::callsite_enabled
373    fn not(self) -> combinator::Not<Self, S>
374    where
375        Self: Sized,
376    {
377        combinator::Not::new(self)
378    }
379
380    /// [Boxes] `self`, erasing its concrete type.
381    ///
382    /// This is equivalent to calling [`Box::new`], but in method form, so that
383    /// it can be used when chaining combinator methods.
384    ///
385    /// # Examples
386    ///
387    /// When different combinations of filters are used conditionally, they may
388    /// have different types. For example, the following code won't compile,
389    /// since the `if` and `else` clause produce filters of different types:
390    ///
391    /// ```compile_fail
392    /// use tracing_subscriber::{
393    ///     filter::{filter_fn, LevelFilter, FilterExt},
394    ///     prelude::*,
395    /// };
396    ///
397    /// let enable_bar_target: bool = // ...
398    /// # false;
399    ///
400    /// let filter = if enable_bar_target {
401    ///     filter_fn(|meta| meta.target().starts_with("foo"))
402    ///         // If `enable_bar_target` is true, add a `filter_fn` enabling
403    ///         // spans and events with the target `bar`:
404    ///         .or(filter_fn(|meta| meta.target().starts_with("bar")))
405    ///         .and(LevelFilter::INFO)
406    /// } else {
407    ///     filter_fn(|meta| meta.target().starts_with("foo"))
408    ///         .and(LevelFilter::INFO)
409    /// };
410    ///
411    /// tracing_subscriber::registry()
412    ///     .with(tracing_subscriber::fmt::layer().with_filter(filter))
413    ///     .init();
414    /// ```
415    ///
416    /// By using `boxed`, the types of the two different branches can be erased,
417    /// so the assignment to the `filter` variable is valid (as both branches
418    /// have the type `Box<dyn Filter<S> + Send + Sync + 'static>`). The
419    /// following code *does* compile:
420    ///
421    /// ```
422    /// use tracing_subscriber::{
423    ///     filter::{filter_fn, LevelFilter, FilterExt},
424    ///     prelude::*,
425    /// };
426    ///
427    /// let enable_bar_target: bool = // ...
428    /// # false;
429    ///
430    /// let filter = if enable_bar_target {
431    ///     filter_fn(|meta| meta.target().starts_with("foo"))
432    ///         .or(filter_fn(|meta| meta.target().starts_with("bar")))
433    ///         .and(LevelFilter::INFO)
434    ///         // Boxing the filter erases its type, so both branches now
435    ///         // have the same type.
436    ///         .boxed()
437    /// } else {
438    ///     filter_fn(|meta| meta.target().starts_with("foo"))
439    ///         .and(LevelFilter::INFO)
440    ///         .boxed()
441    /// };
442    ///
443    /// tracing_subscriber::registry()
444    ///     .with(tracing_subscriber::fmt::layer().with_filter(filter))
445    ///     .init();
446    /// ```
447    ///
448    /// [Boxes]: std::boxed
449    /// [`Box::new`]: std::boxed::Box::new
450    fn boxed(self) -> Box<dyn layer::Filter<S> + Send + Sync + 'static>
451    where
452        Self: Sized + Send + Sync + 'static,
453    {
454        Box::new(self)
455    }
456}
457
458// === impl Filter ===
459
460#[cfg(feature = "registry")]
461#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
462impl<S> layer::Filter<S> for LevelFilter {
463    fn enabled(&self, meta: &Metadata<'_>, _: &Context<'_, S>) -> bool {
464        meta.level() <= self
465    }
466
467    fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
468        if meta.level() <= self {
469            Interest::always()
470        } else {
471            Interest::never()
472        }
473    }
474
475    fn max_level_hint(&self) -> Option<LevelFilter> {
476        Some(*self)
477    }
478}
479
480macro_rules! filter_impl_body {
481    () => {
482        #[inline]
483        fn enabled(&self, meta: &Metadata<'_>, cx: &Context<'_, S>) -> bool {
484            self.deref().enabled(meta, cx)
485        }
486
487        #[inline]
488        fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
489            self.deref().callsite_enabled(meta)
490        }
491
492        #[inline]
493        fn max_level_hint(&self) -> Option<LevelFilter> {
494            self.deref().max_level_hint()
495        }
496
497        #[inline]
498        fn event_enabled(&self, event: &Event<'_>, cx: &Context<'_, S>) -> bool {
499            self.deref().event_enabled(event, cx)
500        }
501
502        #[inline]
503        fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
504            self.deref().on_new_span(attrs, id, ctx)
505        }
506
507        #[inline]
508        fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
509            self.deref().on_record(id, values, ctx)
510        }
511
512        #[inline]
513        fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
514            self.deref().on_enter(id, ctx)
515        }
516
517        #[inline]
518        fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
519            self.deref().on_exit(id, ctx)
520        }
521
522        #[inline]
523        fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
524            self.deref().on_close(id, ctx)
525        }
526    };
527}
528
529#[cfg(feature = "registry")]
530#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
531impl<S> layer::Filter<S> for Arc<dyn layer::Filter<S> + Send + Sync + 'static> {
532    filter_impl_body!();
533}
534
535#[cfg(feature = "registry")]
536#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
537impl<S> layer::Filter<S> for Box<dyn layer::Filter<S> + Send + Sync + 'static> {
538    filter_impl_body!();
539}
540
541// Implement Filter for Option<Filter> where None => allow
542#[cfg(feature = "registry")]
543#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
544impl<F, S> layer::Filter<S> for Option<F>
545where
546    F: layer::Filter<S>,
547{
548    #[inline]
549    fn enabled(&self, meta: &Metadata<'_>, ctx: &Context<'_, S>) -> bool {
550        self.as_ref()
551            .map(|inner| inner.enabled(meta, ctx))
552            .unwrap_or(true)
553    }
554
555    #[inline]
556    fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
557        self.as_ref()
558            .map(|inner| inner.callsite_enabled(meta))
559            .unwrap_or_else(Interest::always)
560    }
561
562    #[inline]
563    fn max_level_hint(&self) -> Option<LevelFilter> {
564        self.as_ref().and_then(|inner| inner.max_level_hint())
565    }
566
567    #[inline]
568    fn event_enabled(&self, event: &Event<'_>, ctx: &Context<'_, S>) -> bool {
569        self.as_ref()
570            .map(|inner| inner.event_enabled(event, ctx))
571            .unwrap_or(true)
572    }
573
574    #[inline]
575    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
576        if let Some(inner) = self {
577            inner.on_new_span(attrs, id, ctx)
578        }
579    }
580
581    #[inline]
582    fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
583        if let Some(inner) = self {
584            inner.on_record(id, values, ctx)
585        }
586    }
587
588    #[inline]
589    fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
590        if let Some(inner) = self {
591            inner.on_enter(id, ctx)
592        }
593    }
594
595    #[inline]
596    fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
597        if let Some(inner) = self {
598            inner.on_exit(id, ctx)
599        }
600    }
601
602    #[inline]
603    fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
604        if let Some(inner) = self {
605            inner.on_close(id, ctx)
606        }
607    }
608}
609
610// === impl Filtered ===
611
612impl<L, F, S> Filtered<L, F, S> {
613    /// Wraps the provided [`Layer`] so that it is filtered by the given
614    /// [`Filter`].
615    ///
616    /// This is equivalent to calling the [`Layer::with_filter`] method.
617    ///
618    /// See the [documentation on per-layer filtering][plf] for details.
619    ///
620    /// [`Filter`]: crate::layer::Filter
621    /// [plf]: crate::layer#per-layer-filtering
622    pub fn new(layer: L, filter: F) -> Self {
623        Self {
624            layer,
625            filter,
626            id: MagicPlfDowncastMarker(FilterId::disabled()),
627            _s: PhantomData,
628        }
629    }
630
631    #[inline(always)]
632    fn id(&self) -> FilterId {
633        debug_assert!(
634            !self.id.0.is_disabled(),
635            "a `Filtered` layer was used, but it had no `FilterId`; \
636            was it registered with the subscriber?"
637        );
638        self.id.0
639    }
640
641    fn did_enable(&self, f: impl FnOnce()) {
642        FILTERING.with(|filtering| filtering.did_enable(self.id(), f))
643    }
644
645    /// Borrows the [`Filter`](crate::layer::Filter) used by this layer.
646    pub fn filter(&self) -> &F {
647        &self.filter
648    }
649
650    /// Mutably borrows the [`Filter`](crate::layer::Filter) used by this layer.
651    ///
652    /// When this layer can be mutably borrowed, this may be used to mutate the filter.
653    /// Generally, this will primarily be used with the
654    /// [`reload::Handle::modify`](crate::reload::Handle::modify) method.
655    ///
656    /// # Examples
657    ///
658    /// ```
659    /// # use tracing::info;
660    /// # use tracing_subscriber::{filter,fmt,reload,Registry,prelude::*};
661    /// # fn main() {
662    /// let filtered_layer = fmt::Layer::default().with_filter(filter::LevelFilter::WARN);
663    /// let (filtered_layer, reload_handle) = reload::Layer::new(filtered_layer);
664    /// #
665    /// # // specifying the Registry type is required
666    /// # let _: &reload::Handle<filter::Filtered<fmt::Layer<Registry>,
667    /// # filter::LevelFilter, Registry>,Registry>
668    /// # = &reload_handle;
669    /// #
670    /// info!("This will be ignored");
671    /// reload_handle.modify(|layer| *layer.filter_mut() = filter::LevelFilter::INFO);
672    /// info!("This will be logged");
673    /// # }
674    /// ```
675    pub fn filter_mut(&mut self) -> &mut F {
676        &mut self.filter
677    }
678
679    /// Borrows the inner [`Layer`] wrapped by this `Filtered` layer.
680    pub fn inner(&self) -> &L {
681        &self.layer
682    }
683
684    /// Mutably borrows the inner [`Layer`] wrapped by this `Filtered` layer.
685    ///
686    /// This method is primarily expected to be used with the
687    /// [`reload::Handle::modify`](crate::reload::Handle::modify) method.
688    ///
689    /// # Examples
690    ///
691    /// ```
692    /// # use tracing::info;
693    /// # use tracing_subscriber::{filter,fmt,reload,Registry,prelude::*};
694    /// # fn non_blocking<T: std::io::Write>(writer: T) -> (fn() -> std::io::Stdout) {
695    /// #   std::io::stdout
696    /// # }
697    /// # fn main() {
698    /// let filtered_layer = fmt::layer().with_writer(non_blocking(std::io::stderr())).with_filter(filter::LevelFilter::INFO);
699    /// let (filtered_layer, reload_handle) = reload::Layer::new(filtered_layer);
700    /// #
701    /// # // specifying the Registry type is required
702    /// # let _: &reload::Handle<filter::Filtered<fmt::Layer<Registry, _, _, fn() -> std::io::Stdout>,
703    /// # filter::LevelFilter, Registry>, Registry>
704    /// # = &reload_handle;
705    /// #
706    /// info!("This will be logged to stderr");
707    /// reload_handle.modify(|layer| *layer.inner_mut().writer_mut() = non_blocking(std::io::stdout()));
708    /// info!("This will be logged to stdout");
709    /// # }
710    /// ```
711    ///
712    /// [`Layer`]: crate::layer::Layer
713    pub fn inner_mut(&mut self) -> &mut L {
714        &mut self.layer
715    }
716}
717
718impl<S, L, F> Layer<S> for Filtered<L, F, S>
719where
720    S: Subscriber + for<'span> registry::LookupSpan<'span> + 'static,
721    F: layer::Filter<S> + 'static,
722    L: Layer<S>,
723{
724    fn on_register_dispatch(&self, subscriber: &Dispatch) {
725        self.layer.on_register_dispatch(subscriber);
726    }
727
728    fn on_layer(&mut self, subscriber: &mut S) {
729        self.id = MagicPlfDowncastMarker(subscriber.register_filter());
730        self.layer.on_layer(subscriber);
731    }
732
733    // TODO(eliza): can we figure out a nice way to make the `Filtered` layer
734    // not call `is_enabled_for` in hooks that the inner layer doesn't actually
735    // have real implementations of? probably not...
736    //
737    // it would be cool if there was some wild rust reflection way of checking
738    // if a trait impl has the default impl of a trait method or not, but that's
739    // almost certainly impossible...right?
740
741    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
742        let interest = self.filter.callsite_enabled(metadata);
743
744        // If the filter didn't disable the callsite, allow the inner layer to
745        // register it — since `register_callsite` is also used for purposes
746        // such as reserving/caching per-callsite data, we want the inner layer
747        // to be able to perform any other registration steps. However, we'll
748        // ignore its `Interest`.
749        if !interest.is_never() {
750            self.layer.register_callsite(metadata);
751        }
752
753        // Add our `Interest` to the current sum of per-layer filter `Interest`s
754        // for this callsite.
755        FILTERING.with(|filtering| filtering.add_interest(interest));
756
757        // don't short circuit! if the stack consists entirely of `Layer`s with
758        // per-layer filters, the `Registry` will return the actual `Interest`
759        // value that's the sum of all the `register_callsite` calls to those
760        // per-layer filters. if we returned an actual `never` interest here, a
761        // `Layered` layer would short-circuit and not allow any `Filtered`
762        // layers below us if _they_ are interested in the callsite.
763        Interest::always()
764    }
765
766    fn enabled(&self, metadata: &Metadata<'_>, cx: Context<'_, S>) -> bool {
767        let cx = cx.with_filter(self.id());
768        let enabled = self.filter.enabled(metadata, &cx);
769        FILTERING.with(|filtering| filtering.set(self.id(), enabled));
770
771        if enabled {
772            // If the filter enabled this metadata, ask the wrapped layer if
773            // _it_ wants it --- it might have a global filter.
774            self.layer.enabled(metadata, cx)
775        } else {
776            // Otherwise, return `true`. The _per-layer_ filter disabled this
777            // metadata, but returning `false` in `Layer::enabled` will
778            // short-circuit and globally disable the span or event. This is
779            // *not* what we want for per-layer filters, as other layers may
780            // still want this event. Returning `true` here means we'll continue
781            // asking the next layer in the stack.
782            //
783            // Once all per-layer filters have been evaluated, the `Registry`
784            // at the root of the stack will return `false` from its `enabled`
785            // method if *every* per-layer  filter disabled this metadata.
786            // Otherwise, the individual per-layer filters will skip the next
787            // `new_span` or `on_event` call for their layer if *they* disabled
788            // the span or event, but it was not globally disabled.
789            true
790        }
791    }
792
793    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, cx: Context<'_, S>) {
794        self.did_enable(|| {
795            let cx = cx.with_filter(self.id());
796            self.filter.on_new_span(attrs, id, cx.clone());
797            self.layer.on_new_span(attrs, id, cx);
798        })
799    }
800
801    #[doc(hidden)]
802    fn max_level_hint(&self) -> Option<LevelFilter> {
803        self.filter.max_level_hint()
804    }
805
806    fn on_record(&self, span: &span::Id, values: &span::Record<'_>, cx: Context<'_, S>) {
807        if let Some(cx) = cx.if_enabled_for(span, self.id()) {
808            self.filter.on_record(span, values, cx.clone());
809            self.layer.on_record(span, values, cx)
810        }
811    }
812
813    fn on_follows_from(&self, span: &span::Id, follows: &span::Id, cx: Context<'_, S>) {
814        // only call `on_follows_from` if both spans are enabled by us
815        if cx.is_enabled_for(span, self.id()) && cx.is_enabled_for(follows, self.id()) {
816            self.layer
817                .on_follows_from(span, follows, cx.with_filter(self.id()))
818        }
819    }
820
821    fn event_enabled(&self, event: &Event<'_>, cx: Context<'_, S>) -> bool {
822        let cx = cx.with_filter(self.id());
823        let enabled = FILTERING
824            .with(|filtering| filtering.and(self.id(), || self.filter.event_enabled(event, &cx)));
825
826        if enabled {
827            // If the filter enabled this event, ask the wrapped subscriber if
828            // _it_ wants it --- it might have a global filter.
829            self.layer.event_enabled(event, cx)
830        } else {
831            // Otherwise, return `true`. See the comment in `enabled` for why this
832            // is necessary.
833            true
834        }
835    }
836
837    fn on_event(&self, event: &Event<'_>, cx: Context<'_, S>) {
838        self.did_enable(|| {
839            self.layer.on_event(event, cx.with_filter(self.id()));
840        })
841    }
842
843    fn on_enter(&self, id: &span::Id, cx: Context<'_, S>) {
844        if let Some(cx) = cx.if_enabled_for(id, self.id()) {
845            self.filter.on_enter(id, cx.clone());
846            self.layer.on_enter(id, cx);
847        }
848    }
849
850    fn on_exit(&self, id: &span::Id, cx: Context<'_, S>) {
851        if let Some(cx) = cx.if_enabled_for(id, self.id()) {
852            self.filter.on_exit(id, cx.clone());
853            self.layer.on_exit(id, cx);
854        }
855    }
856
857    fn on_close(&self, id: span::Id, cx: Context<'_, S>) {
858        if let Some(cx) = cx.if_enabled_for(&id, self.id()) {
859            self.filter.on_close(id.clone(), cx.clone());
860            self.layer.on_close(id, cx);
861        }
862    }
863
864    // XXX(eliza): the existence of this method still makes me sad...
865    fn on_id_change(&self, old: &span::Id, new: &span::Id, cx: Context<'_, S>) {
866        if let Some(cx) = cx.if_enabled_for(old, self.id()) {
867            self.layer.on_id_change(old, new, cx)
868        }
869    }
870
871    #[doc(hidden)]
872    #[inline]
873    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
874        match id {
875            id if id == TypeId::of::<Self>() => Some(self as *const _ as *const ()),
876            id if id == TypeId::of::<L>() => Some(&self.layer as *const _ as *const ()),
877            id if id == TypeId::of::<F>() => Some(&self.filter as *const _ as *const ()),
878            id if id == TypeId::of::<MagicPlfDowncastMarker>() => {
879                Some(&self.id as *const _ as *const ())
880            }
881            _ => unsafe { self.layer.downcast_raw(id) },
882        }
883    }
884}
885
886impl<F, L, S> fmt::Debug for Filtered<F, L, S>
887where
888    F: fmt::Debug,
889    L: fmt::Debug,
890{
891    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892        f.debug_struct("Filtered")
893            .field("filter", &self.filter)
894            .field("layer", &self.layer)
895            .field("id", &self.id)
896            .finish()
897    }
898}
899
900// === impl FilterId ===
901
902impl FilterId {
903    const fn disabled() -> Self {
904        Self(u64::MAX)
905    }
906
907    /// Returns a `FilterId` that will consider _all_ spans enabled.
908    pub(crate) const fn none() -> Self {
909        Self(0)
910    }
911
912    pub(crate) fn new(id: u8) -> Self {
913        assert!(id < 64, "filter IDs may not be greater than 64");
914        Self(1 << id as usize)
915    }
916
917    /// Combines two `FilterId`s, returning a new `FilterId` that will match a
918    /// [`FilterMap`] where the span was disabled by _either_ this `FilterId`
919    /// *or* the combined `FilterId`.
920    ///
921    /// This method is called by [`Context`]s when adding the `FilterId` of a
922    /// [`Filtered`] layer to the context.
923    ///
924    /// This is necessary for cases where we have a tree of nested [`Filtered`]
925    /// layers, like this:
926    ///
927    /// ```text
928    /// Filtered {
929    ///     filter1,
930    ///     Layered {
931    ///         layer1,
932    ///         Filtered {
933    ///              filter2,
934    ///              layer2,
935    ///         },
936    /// }
937    /// ```
938    ///
939    /// We want `layer2` to be affected by both `filter1` _and_ `filter2`.
940    /// Without combining `FilterId`s, this works fine when filtering
941    /// `on_event`/`new_span`, because the outer `Filtered` layer (`filter1`)
942    /// won't call the inner layer's `on_event` or `new_span` callbacks if it
943    /// disabled the event/span.
944    ///
945    /// However, it _doesn't_ work when filtering span lookups and traversals
946    /// (e.g. `scope`). This is because the [`Context`] passed to `layer2`
947    /// would set its filter ID to the filter ID of `filter2`, and would skip
948    /// spans that were disabled by `filter2`. However, what if a span was
949    /// disabled by `filter1`? We wouldn't see it in `new_span`, but we _would_
950    /// see it in lookups and traversals...which we don't want.
951    ///
952    /// When a [`Filtered`] layer adds its ID to a [`Context`], it _combines_ it
953    /// with any previous filter ID that the context had, rather than replacing
954    /// it. That way, `layer2`'s context will check if a span was disabled by
955    /// `filter1` _or_ `filter2`. The way we do this, instead of representing
956    /// `FilterId`s as a number number that we shift a 1 over by to get a mask,
957    /// we just store the actual mask,so we can combine them with a bitwise-OR.
958    ///
959    /// For example, if we consider the following case (pretending that the
960    /// masks are 8 bits instead of 64 just so i don't have to write out a bunch
961    /// of extra zeroes):
962    ///
963    /// - `filter1` has the filter id 1 (`0b0000_0001`)
964    /// - `filter2` has the filter id 2 (`0b0000_0010`)
965    ///
966    /// A span that gets disabled by filter 1 would have the [`FilterMap`] with
967    /// bits `0b0000_0001`.
968    ///
969    /// If the `FilterId` was internally represented as `(bits to shift + 1),
970    /// when `layer2`'s [`Context`] checked if it enabled the  span, it would
971    /// make the mask `0b0000_0010` (`1 << 1`). That bit would not be set in the
972    /// [`FilterMap`], so it would see that it _didn't_ disable  the span. Which
973    /// is *true*, it just doesn't reflect the tree-like shape of the actual
974    /// subscriber.
975    ///
976    /// By having the IDs be masks instead of shifts, though, when the
977    /// [`Filtered`] with `filter2` gets the [`Context`] with `filter1`'s filter ID,
978    /// instead of replacing it, it ors them together:
979    ///
980    /// ```ignore
981    /// 0b0000_0001 | 0b0000_0010 == 0b0000_0011;
982    /// ```
983    ///
984    /// We then test if the span was disabled by  seeing if _any_ bits in the
985    /// mask are `1`:
986    ///
987    /// ```ignore
988    /// filtermap & mask != 0;
989    /// 0b0000_0001 & 0b0000_0011 != 0;
990    /// 0b0000_0001 != 0;
991    /// true;
992    /// ```
993    ///
994    /// [`Context`]: crate::layer::Context
995    pub(crate) fn and(self, FilterId(other): Self) -> Self {
996        // If this mask is disabled, just return the other --- otherwise, we
997        // would always see that every span is disabled.
998        if self.0 == Self::disabled().0 {
999            return Self(other);
1000        }
1001
1002        Self(self.0 | other)
1003    }
1004
1005    fn is_disabled(self) -> bool {
1006        self.0 == Self::disabled().0
1007    }
1008}
1009
1010impl fmt::Debug for FilterId {
1011    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012        // don't print a giant set of the numbers 0..63 if the filter ID is disabled.
1013        if self.0 == Self::disabled().0 {
1014            return f
1015                .debug_tuple("FilterId")
1016                .field(&format_args!("DISABLED"))
1017                .finish();
1018        }
1019
1020        if f.alternate() {
1021            f.debug_struct("FilterId")
1022                .field("ids", &format_args!("{:?}", FmtBitset(self.0)))
1023                .field("bits", &format_args!("{:b}", self.0))
1024                .finish()
1025        } else {
1026            f.debug_tuple("FilterId").field(&FmtBitset(self.0)).finish()
1027        }
1028    }
1029}
1030
1031impl fmt::Binary for FilterId {
1032    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1033        f.debug_tuple("FilterId")
1034            .field(&format_args!("{:b}", self.0))
1035            .finish()
1036    }
1037}
1038
1039// === impl FilterExt ===
1040
1041impl<F, S> FilterExt<S> for F where F: layer::Filter<S> {}
1042
1043// === impl FilterMap ===
1044
1045impl FilterMap {
1046    pub(crate) fn set(self, FilterId(mask): FilterId, enabled: bool) -> Self {
1047        if mask == u64::MAX {
1048            return self;
1049        }
1050
1051        if enabled {
1052            Self {
1053                bits: self.bits & (!mask),
1054            }
1055        } else {
1056            Self {
1057                bits: self.bits | mask,
1058            }
1059        }
1060    }
1061
1062    #[inline]
1063    pub(crate) fn is_enabled(self, FilterId(mask): FilterId) -> bool {
1064        self.bits & mask == 0
1065    }
1066
1067    #[inline]
1068    pub(crate) fn any_enabled(self) -> bool {
1069        self.bits != u64::MAX
1070    }
1071}
1072
1073impl fmt::Debug for FilterMap {
1074    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1075        let alt = f.alternate();
1076        let mut s = f.debug_struct("FilterMap");
1077        s.field("disabled_by", &format_args!("{:?}", &FmtBitset(self.bits)));
1078
1079        if alt {
1080            s.field("bits", &format_args!("{:b}", self.bits));
1081        }
1082
1083        s.finish()
1084    }
1085}
1086
1087impl fmt::Binary for FilterMap {
1088    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1089        f.debug_struct("FilterMap")
1090            .field("bits", &format_args!("{:b}", self.bits))
1091            .finish()
1092    }
1093}
1094
1095// === impl FilterState ===
1096
1097impl FilterState {
1098    const fn new() -> Self {
1099        Self {
1100            enabled: Cell::new(FilterMap::new()),
1101            interest: RefCell::new(None),
1102
1103            #[cfg(debug_assertions)]
1104            counters: DebugCounters::new(),
1105        }
1106    }
1107
1108    fn set(&self, filter: FilterId, enabled: bool) {
1109        #[cfg(debug_assertions)]
1110        {
1111            let in_current_pass = self.counters.in_filter_pass.get();
1112            if in_current_pass == 0 {
1113                debug_assert_eq!(self.enabled.get(), FilterMap::new());
1114            }
1115            self.counters.in_filter_pass.set(in_current_pass + 1);
1116            debug_assert_eq!(
1117                self.counters.in_interest_pass.get(),
1118                0,
1119                "if we are in or starting a filter pass, we must not be in an interest pass."
1120            )
1121        }
1122
1123        self.enabled.set(self.enabled.get().set(filter, enabled))
1124    }
1125
1126    fn add_interest(&self, interest: Interest) {
1127        let mut curr_interest = self.interest.borrow_mut();
1128
1129        #[cfg(debug_assertions)]
1130        {
1131            let in_current_pass = self.counters.in_interest_pass.get();
1132            if in_current_pass == 0 {
1133                debug_assert!(curr_interest.is_none());
1134            }
1135            self.counters.in_interest_pass.set(in_current_pass + 1);
1136        }
1137
1138        if let Some(curr_interest) = curr_interest.as_mut() {
1139            if (curr_interest.is_always() && !interest.is_always())
1140                || (curr_interest.is_never() && !interest.is_never())
1141            {
1142                *curr_interest = Interest::sometimes();
1143            }
1144            // If the two interests are the same, do nothing. If the current
1145            // interest is `sometimes`, stay sometimes.
1146        } else {
1147            *curr_interest = Some(interest);
1148        }
1149    }
1150
1151    pub(crate) fn event_enabled() -> bool {
1152        FILTERING
1153            .try_with(|this| {
1154                let enabled = this.enabled.get().any_enabled();
1155                #[cfg(debug_assertions)]
1156                {
1157                    if this.counters.in_filter_pass.get() == 0 {
1158                        debug_assert_eq!(this.enabled.get(), FilterMap::new());
1159                    }
1160
1161                    // Nothing enabled this event, we won't tick back down the
1162                    // counter in `did_enable`. Reset it.
1163                    if !enabled {
1164                        this.counters.in_filter_pass.set(0);
1165                    }
1166                }
1167                enabled
1168            })
1169            .unwrap_or(true)
1170    }
1171
1172    /// Executes a closure if the filter with the provided ID did not disable
1173    /// the current span/event.
1174    ///
1175    /// This is used to implement the `on_event` and `new_span` methods for
1176    /// `Filtered`.
1177    fn did_enable(&self, filter: FilterId, f: impl FnOnce()) {
1178        let map = self.enabled.get();
1179        if map.is_enabled(filter) {
1180            // If the filter didn't disable the current span/event, run the
1181            // callback.
1182            f();
1183        } else {
1184            // Otherwise, if this filter _did_ disable the span or event
1185            // currently being processed, clear its bit from this thread's
1186            // `FilterState`. The bit has already been "consumed" by skipping
1187            // this callback, and we need to ensure that the `FilterMap` for
1188            // this thread is reset when the *next* `enabled` call occurs.
1189            self.enabled.set(map.set(filter, true));
1190        }
1191        #[cfg(debug_assertions)]
1192        {
1193            let in_current_pass = self.counters.in_filter_pass.get();
1194            if in_current_pass <= 1 {
1195                debug_assert_eq!(self.enabled.get(), FilterMap::new());
1196            }
1197            self.counters
1198                .in_filter_pass
1199                .set(in_current_pass.saturating_sub(1));
1200            debug_assert_eq!(
1201                self.counters.in_interest_pass.get(),
1202                0,
1203                "if we are in a filter pass, we must not be in an interest pass."
1204            )
1205        }
1206    }
1207
1208    /// Run a second filtering pass, e.g. for Layer::event_enabled.
1209    fn and(&self, filter: FilterId, f: impl FnOnce() -> bool) -> bool {
1210        let map = self.enabled.get();
1211        let enabled = map.is_enabled(filter) && f();
1212        self.enabled.set(map.set(filter, enabled));
1213        enabled
1214    }
1215
1216    /// Clears the current in-progress filter state.
1217    ///
1218    /// This resets the [`FilterMap`] and current [`Interest`] as well as
1219    /// clearing the debug counters.
1220    pub(crate) fn clear_enabled() {
1221        // Drop the `Result` returned by `try_with` --- if we are in the middle
1222        // a panic and the thread-local has been torn down, that's fine, just
1223        // ignore it ratehr than panicking.
1224        let _ = FILTERING.try_with(|filtering| {
1225            filtering.enabled.set(FilterMap::new());
1226
1227            #[cfg(debug_assertions)]
1228            filtering.counters.in_filter_pass.set(0);
1229        });
1230    }
1231
1232    pub(crate) fn take_interest() -> Option<Interest> {
1233        FILTERING
1234            .try_with(|filtering| {
1235                #[cfg(debug_assertions)]
1236                {
1237                    if filtering.counters.in_interest_pass.get() == 0 {
1238                        debug_assert!(filtering.interest.try_borrow().ok()?.is_none());
1239                    }
1240                    filtering.counters.in_interest_pass.set(0);
1241                }
1242                filtering.interest.try_borrow_mut().ok()?.take()
1243            })
1244            .ok()?
1245    }
1246
1247    pub(crate) fn filter_map(&self) -> FilterMap {
1248        let map = self.enabled.get();
1249        #[cfg(debug_assertions)]
1250        if self.counters.in_filter_pass.get() == 0 {
1251            debug_assert_eq!(map, FilterMap::new());
1252        }
1253
1254        map
1255    }
1256}
1257/// This is a horrible and bad abuse of the downcasting system to expose
1258/// *internally* whether a layer has per-layer filtering, within
1259/// `tracing-subscriber`, without exposing a public API for it.
1260///
1261/// If a `Layer` has per-layer filtering, it will downcast to a
1262/// `MagicPlfDowncastMarker`. Since layers which contain other layers permit
1263/// downcasting to recurse to their children, this will do the Right Thing with
1264/// layers like Reload, Option, etc.
1265///
1266/// Why is this a wrapper around the `FilterId`, you may ask? Because
1267/// downcasting works by returning a pointer, and we don't want to risk
1268/// introducing UB by  constructing pointers that _don't_ point to a valid
1269/// instance of the type they claim to be. In this case, we don't _intend_ for
1270/// this pointer to be dereferenced, so it would actually be fine to return one
1271/// that isn't a valid pointer...but we can't guarantee that the caller won't
1272/// (accidentally) dereference it, so it's better to be safe than sorry. We
1273/// could, alternatively, add an additional field to the type that's used only
1274/// for returning pointers to as as part of the evil downcasting hack, but I
1275/// thought it was nicer to just add a `repr(transparent)` wrapper to the
1276/// existing `FilterId` field, since it won't make the struct any bigger.
1277///
1278/// Don't worry, this isn't on the test. :)
1279#[derive(Clone, Copy)]
1280#[repr(transparent)]
1281struct MagicPlfDowncastMarker(FilterId);
1282impl fmt::Debug for MagicPlfDowncastMarker {
1283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1284        // Just pretend that `MagicPlfDowncastMarker` doesn't exist for
1285        // `fmt::Debug` purposes...if no one *sees* it in their `Debug` output,
1286        // they don't have to know I thought this code would be a good idea.
1287        fmt::Debug::fmt(&self.0, f)
1288    }
1289}
1290
1291pub(crate) fn is_plf_downcast_marker(type_id: TypeId) -> bool {
1292    type_id == TypeId::of::<MagicPlfDowncastMarker>()
1293}
1294
1295/// Does a type implementing `Subscriber` contain any per-layer filters?
1296pub(crate) fn subscriber_has_plf<S>(subscriber: &S) -> bool
1297where
1298    S: Subscriber,
1299{
1300    (subscriber as &dyn Subscriber).is::<MagicPlfDowncastMarker>()
1301}
1302
1303/// Does a type implementing `Layer` contain any per-layer filters?
1304pub(crate) fn layer_has_plf<L, S>(layer: &L) -> bool
1305where
1306    L: Layer<S>,
1307    S: Subscriber,
1308{
1309    unsafe {
1310        // Safety: we're not actually *doing* anything with this pointer --- we
1311        // only care about the `Option`, which we're turning into a `bool`. So
1312        // even if the layer decides to be evil and give us some kind of invalid
1313        // pointer, we don't ever dereference it, so this is always safe.
1314        layer.downcast_raw(TypeId::of::<MagicPlfDowncastMarker>())
1315    }
1316    .is_some()
1317}
1318
1319struct FmtBitset(u64);
1320
1321impl fmt::Debug for FmtBitset {
1322    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1323        let mut set = f.debug_set();
1324        for bit in 0..64 {
1325            // if the `bit`-th bit is set, add it to the debug set
1326            if self.0 & (1 << bit) != 0 {
1327                set.entry(&bit);
1328            }
1329        }
1330        set.finish()
1331    }
1332}