🛈 Note: This is pre-release documentation for the upcoming tracing 0.2.0 ecosystem.

For the release documentation, please see docs.rs, instead.

tracing_subscriber/filter/subscriber_filters/
mod.rs

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