tracing_subscriber/layer/
layered.rs

1use tracing_core::{metadata::Metadata, span, Dispatch, Event, Interest, LevelFilter, Subscriber};
2
3use crate::{
4    filter,
5    layer::{Context, Layer},
6    registry::LookupSpan,
7};
8#[cfg(all(feature = "registry", feature = "std"))]
9use crate::{filter::FilterId, registry::Registry};
10use core::{
11    any::{Any, TypeId},
12    cmp, fmt,
13    marker::PhantomData,
14};
15
16/// A [`Subscriber`] composed of a `Subscriber` wrapped by one or more
17/// [`Layer`]s.
18///
19/// [`Layer`]: crate::Layer
20/// [`Subscriber`]: tracing_core::Subscriber
21#[derive(Clone)]
22pub struct Layered<L, I, S = I> {
23    /// The layer.
24    layer: L,
25
26    /// The inner value that `self.layer` was layered onto.
27    ///
28    /// If this is also a `Layer`, then this `Layered` will implement `Layer`.
29    /// If this is a `Subscriber`, then this `Layered` will implement
30    /// `Subscriber` instead.
31    inner: I,
32
33    // These booleans are used to determine how to combine `Interest`s and max
34    // level hints when per-layer filters are in use.
35    /// Is `self.inner` a `Registry`?
36    ///
37    /// If so, when combining `Interest`s, we want to "bubble up" its
38    /// `Interest`.
39    inner_is_registry: bool,
40
41    /// Does `self.layer` have per-layer filters?
42    ///
43    /// This will be true if:
44    /// - `self.inner` is a `Filtered`.
45    /// - `self.inner` is a tree of `Layered`s where _all_ arms of those
46    ///   `Layered`s have per-layer filters.
47    ///
48    /// Otherwise, if it's a `Layered` with one per-layer filter in one branch,
49    /// but a non-per-layer-filtered layer in the other branch, this will be
50    /// _false_, because the `Layered` is already handling the combining of
51    /// per-layer filter `Interest`s and max level hints with its non-filtered
52    /// `Layer`.
53    has_layer_filter: bool,
54
55    /// Does `self.inner` have per-layer filters?
56    ///
57    /// This is determined according to the same rules as
58    /// `has_layer_filter` above.
59    inner_has_layer_filter: bool,
60    _s: PhantomData<fn(S)>,
61}
62
63// === impl Layered ===
64
65impl<L, S> Layered<L, S>
66where
67    L: Layer<S>,
68    S: Subscriber,
69{
70    /// Returns `true` if this [`Subscriber`] is the same type as `T`.
71    pub fn is<T: Any>(&self) -> bool {
72        self.downcast_ref::<T>().is_some()
73    }
74
75    /// Returns some reference to this [`Subscriber`] value if it is of type `T`,
76    /// or `None` if it isn't.
77    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
78        unsafe {
79            let raw = self.downcast_raw(TypeId::of::<T>())?;
80            if raw.is_null() {
81                None
82            } else {
83                Some(&*(raw as *const T))
84            }
85        }
86    }
87}
88
89impl<L, S> Subscriber for Layered<L, S>
90where
91    L: Layer<S>,
92    S: Subscriber,
93{
94    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
95        self.pick_interest(self.layer.register_callsite(metadata), || {
96            self.inner.register_callsite(metadata)
97        })
98    }
99
100    fn enabled(&self, metadata: &Metadata<'_>) -> bool {
101        if self.layer.enabled(metadata, self.ctx()) {
102            // if the outer layer enables the callsite metadata, ask the subscriber.
103            self.inner.enabled(metadata)
104        } else {
105            // otherwise, the callsite is disabled by the layer
106
107            // If per-layer filters are in use, and we are short-circuiting
108            // (rather than calling into the inner type), clear the current
109            // per-layer filter `enabled` state.
110            #[cfg(feature = "registry")]
111            filter::FilterState::clear_enabled();
112
113            false
114        }
115    }
116
117    fn max_level_hint(&self) -> Option<LevelFilter> {
118        self.pick_level_hint(
119            self.layer.max_level_hint(),
120            self.inner.max_level_hint(),
121            super::subscriber_is_none(&self.inner),
122        )
123    }
124
125    fn new_span(&self, span: &span::Attributes<'_>) -> span::Id {
126        let id = self.inner.new_span(span);
127        self.layer.on_new_span(span, &id, self.ctx());
128        id
129    }
130
131    fn record(&self, span: &span::Id, values: &span::Record<'_>) {
132        self.inner.record(span, values);
133        self.layer.on_record(span, values, self.ctx());
134    }
135
136    fn record_follows_from(&self, span: &span::Id, follows: &span::Id) {
137        self.inner.record_follows_from(span, follows);
138        self.layer.on_follows_from(span, follows, self.ctx());
139    }
140
141    fn event_enabled(&self, event: &Event<'_>) -> bool {
142        if self.layer.event_enabled(event, self.ctx()) {
143            // if the outer layer enables the event, ask the inner subscriber.
144            self.inner.event_enabled(event)
145        } else {
146            // otherwise, the event is disabled by this layer
147            false
148        }
149    }
150
151    fn event(&self, event: &Event<'_>) {
152        self.inner.event(event);
153        self.layer.on_event(event, self.ctx());
154    }
155
156    fn enter(&self, span: &span::Id) {
157        self.inner.enter(span);
158        self.layer.on_enter(span, self.ctx());
159    }
160
161    fn exit(&self, span: &span::Id) {
162        self.inner.exit(span);
163        self.layer.on_exit(span, self.ctx());
164    }
165
166    fn clone_span(&self, old: &span::Id) -> span::Id {
167        let new = self.inner.clone_span(old);
168        if &new != old {
169            self.layer.on_id_change(old, &new, self.ctx())
170        };
171        new
172    }
173
174    #[inline]
175    fn drop_span(&self, id: span::Id) {
176        self.try_close(id);
177    }
178
179    fn try_close(&self, id: span::Id) -> bool {
180        #[cfg(all(feature = "registry", feature = "std"))]
181        let subscriber = &self.inner as &dyn Subscriber;
182        #[cfg(all(feature = "registry", feature = "std"))]
183        let mut guard = subscriber
184            .downcast_ref::<Registry>()
185            .map(|registry| registry.start_close(id.clone()));
186        if self.inner.try_close(id.clone()) {
187            // If we have a registry's close guard, indicate that the span is
188            // closing.
189            #[cfg(all(feature = "registry", feature = "std"))]
190            {
191                if let Some(g) = guard.as_mut() {
192                    g.set_closing()
193                };
194            }
195
196            self.layer.on_close(id, self.ctx());
197            true
198        } else {
199            false
200        }
201    }
202
203    #[inline]
204    fn current_span(&self) -> span::Current {
205        self.inner.current_span()
206    }
207
208    #[doc(hidden)]
209    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
210        // Unlike the implementation of `Layer` for `Layered`, we don't have to
211        // handle the "magic PLF downcast marker" here. If a `Layered`
212        // implements `Subscriber`, we already know that the `inner` branch is
213        // going to contain something that doesn't have per-layer filters (the
214        // actual root `Subscriber`). Thus, a `Layered` that implements
215        // `Subscriber` will always be propagating the root subscriber's
216        // `Interest`/level hint, even if it includes a `Layer` that has
217        // per-layer filters, because it will only ever contain layers where
218        // _one_ child has per-layer filters.
219        //
220        // The complex per-layer filter detection logic is only relevant to
221        // *trees* of layers, which involve the `Layer` implementation for
222        // `Layered`, not *lists* of layers, where every `Layered` implements
223        // `Subscriber`. Of course, a linked list can be thought of as a
224        // degenerate tree...but luckily, we are able to make a type-level
225        // distinction between individual `Layered`s that are definitely
226        // list-shaped (their inner child implements `Subscriber`), and
227        // `Layered`s that might be tree-shaped (the inner child is also a
228        // `Layer`).
229
230        // If downcasting to `Self`, return a pointer to `self`.
231        if id == TypeId::of::<Self>() {
232            return Some(self as *const _ as *const ());
233        }
234
235        unsafe { self.layer.downcast_raw(id) }.or_else(|| unsafe { self.inner.downcast_raw(id) })
236    }
237}
238
239impl<S, A, B> Layer<S> for Layered<A, B, S>
240where
241    A: Layer<S>,
242    B: Layer<S>,
243    S: Subscriber,
244{
245    fn on_register_dispatch(&self, subscriber: &Dispatch) {
246        self.layer.on_register_dispatch(subscriber);
247        self.inner.on_register_dispatch(subscriber);
248    }
249
250    fn on_layer(&mut self, subscriber: &mut S) {
251        self.layer.on_layer(subscriber);
252        self.inner.on_layer(subscriber);
253    }
254
255    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
256        self.pick_interest(self.layer.register_callsite(metadata), || {
257            self.inner.register_callsite(metadata)
258        })
259    }
260
261    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
262        if self.layer.enabled(metadata, ctx.clone()) {
263            // if the outer subscriber enables the callsite metadata, ask the inner layer.
264            self.inner.enabled(metadata, ctx)
265        } else {
266            // otherwise, the callsite is disabled by this layer
267            false
268        }
269    }
270
271    fn max_level_hint(&self) -> Option<LevelFilter> {
272        self.pick_level_hint(
273            self.layer.max_level_hint(),
274            self.inner.max_level_hint(),
275            super::layer_is_none(&self.inner),
276        )
277    }
278
279    #[inline]
280    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
281        self.inner.on_new_span(attrs, id, ctx.clone());
282        self.layer.on_new_span(attrs, id, ctx);
283    }
284
285    #[inline]
286    fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
287        self.inner.on_record(span, values, ctx.clone());
288        self.layer.on_record(span, values, ctx);
289    }
290
291    #[inline]
292    fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
293        self.inner.on_follows_from(span, follows, ctx.clone());
294        self.layer.on_follows_from(span, follows, ctx);
295    }
296
297    #[inline]
298    fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
299        if self.layer.event_enabled(event, ctx.clone()) {
300            // if the outer layer enables the event, ask the inner subscriber.
301            self.inner.event_enabled(event, ctx)
302        } else {
303            // otherwise, the event is disabled by this layer
304            false
305        }
306    }
307
308    #[inline]
309    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
310        self.inner.on_event(event, ctx.clone());
311        self.layer.on_event(event, ctx);
312    }
313
314    #[inline]
315    fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
316        self.inner.on_enter(id, ctx.clone());
317        self.layer.on_enter(id, ctx);
318    }
319
320    #[inline]
321    fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
322        self.inner.on_exit(id, ctx.clone());
323        self.layer.on_exit(id, ctx);
324    }
325
326    #[inline]
327    fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
328        self.inner.on_close(id.clone(), ctx.clone());
329        self.layer.on_close(id, ctx);
330    }
331
332    #[inline]
333    fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
334        self.inner.on_id_change(old, new, ctx.clone());
335        self.layer.on_id_change(old, new, ctx);
336    }
337
338    #[doc(hidden)]
339    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
340        match id {
341            // If downcasting to `Self`, return a pointer to `self`.
342            id if id == TypeId::of::<Self>() => Some(self as *const _ as *const ()),
343
344            // Oh, we're looking for per-layer filters!
345            //
346            // This should only happen if we are inside of another `Layered`,
347            // and it's trying to determine how it should combine `Interest`s
348            // and max level hints.
349            //
350            // In that case, this `Layered` should be considered to be
351            // "per-layer filtered" if *both* the outer layer and the inner
352            // layer/subscriber have per-layer filters. Otherwise, this `Layered
353            // should *not* be considered per-layer filtered (even if one or the
354            // other has per layer filters). If only one `Layer` is per-layer
355            // filtered, *this* `Layered` will handle aggregating the `Interest`
356            // and level hints on behalf of its children, returning the
357            // aggregate (which is the value from the &non-per-layer-filtered*
358            // child).
359            //
360            // Yes, this rule *is* slightly counter-intuitive, but it's
361            // necessary due to a weird edge case that can occur when two
362            // `Layered`s where one side is per-layer filtered and the other
363            // isn't are `Layered` together to form a tree. If we didn't have
364            // this rule, we would actually end up *ignoring* `Interest`s from
365            // the non-per-layer-filtered layers, since both branches would
366            // claim to have PLF.
367            //
368            // If you don't understand this...that's fine, just don't mess with
369            // it. :)
370            id if filter::is_plf_downcast_marker(id) => {
371                unsafe { self.layer.downcast_raw(id) }.and(unsafe { self.inner.downcast_raw(id) })
372            }
373
374            // Otherwise, try to downcast both branches normally...
375            _ => unsafe { self.layer.downcast_raw(id) }
376                .or_else(|| unsafe { self.inner.downcast_raw(id) }),
377        }
378    }
379}
380
381impl<'a, L, S> LookupSpan<'a> for Layered<L, S>
382where
383    S: Subscriber + LookupSpan<'a>,
384{
385    type Data = S::Data;
386
387    fn span_data(&'a self, id: &span::Id) -> Option<Self::Data> {
388        self.inner.span_data(id)
389    }
390
391    #[cfg(all(feature = "registry", feature = "std"))]
392    fn register_filter(&mut self) -> FilterId {
393        self.inner.register_filter()
394    }
395}
396
397impl<L, S> Layered<L, S>
398where
399    S: Subscriber,
400{
401    fn ctx(&self) -> Context<'_, S> {
402        Context::new(&self.inner)
403    }
404}
405
406impl<A, B, S> Layered<A, B, S>
407where
408    A: Layer<S>,
409    S: Subscriber,
410{
411    pub(super) fn new(layer: A, inner: B, inner_has_layer_filter: bool) -> Self {
412        #[cfg(all(feature = "registry", feature = "std"))]
413        let inner_is_registry = TypeId::of::<S>() == TypeId::of::<crate::registry::Registry>();
414
415        #[cfg(not(all(feature = "registry", feature = "std")))]
416        let inner_is_registry = false;
417
418        let inner_has_layer_filter = inner_has_layer_filter || inner_is_registry;
419        let has_layer_filter = filter::layer_has_plf(&layer);
420        Self {
421            layer,
422            inner,
423            has_layer_filter,
424            inner_has_layer_filter,
425            inner_is_registry,
426            _s: PhantomData,
427        }
428    }
429
430    fn pick_interest(&self, outer: Interest, inner: impl FnOnce() -> Interest) -> Interest {
431        if self.has_layer_filter {
432            return inner();
433        }
434
435        // If the outer layer has disabled the callsite, return now so that
436        // the inner layer/subscriber doesn't get its hopes up.
437        if outer.is_never() {
438            // If per-layer filters are in use, and we are short-circuiting
439            // (rather than calling into the inner type), clear the current
440            // per-layer filter interest state.
441            #[cfg(feature = "registry")]
442            filter::FilterState::take_interest();
443
444            return outer;
445        }
446
447        // The `inner` closure will call `inner.register_callsite()`. We do this
448        // before the `if` statement to  ensure that the inner subscriber is
449        // informed that the callsite exists regardless of the outer layer's
450        // filtering decision.
451        let inner = inner();
452        if outer.is_sometimes() {
453            // if this interest is "sometimes", return "sometimes" to ensure that
454            // filters are reevaluated.
455            return outer;
456        }
457
458        // If there is a per-layer filter in the `inner` stack, and it returns
459        // `never`, change the interest to `sometimes`, because the `outer`
460        // layer didn't return `never`. This means that _some_ layer still wants
461        // to see that callsite, even though the inner stack's per-layer filter
462        // didn't want it. Therefore, returning `sometimes` will ensure
463        // `enabled` is called so that the per-layer filter can skip that
464        // span/event, while the `outer` layer still gets to see it.
465        if inner.is_never() && self.inner_has_layer_filter {
466            return Interest::sometimes();
467        }
468
469        // otherwise, allow the inner subscriber or subscriber to weigh in.
470        inner
471    }
472
473    fn pick_level_hint(
474        &self,
475        outer_hint: Option<LevelFilter>,
476        inner_hint: Option<LevelFilter>,
477        inner_is_none: bool,
478    ) -> Option<LevelFilter> {
479        if self.inner_is_registry {
480            return outer_hint;
481        }
482
483        if self.has_layer_filter && self.inner_has_layer_filter {
484            return Some(cmp::max(outer_hint?, inner_hint?));
485        }
486
487        if self.has_layer_filter && inner_hint.is_none() {
488            return None;
489        }
490
491        if self.inner_has_layer_filter && outer_hint.is_none() {
492            return None;
493        }
494
495        // If the layer is `Option::None`, then we
496        // want to short-circuit the layer underneath, if it
497        // returns `None`, to override the `None` layer returning
498        // `Some(OFF)`, which should ONLY apply when there are
499        // no other layers that return `None`. Note this
500        // `None` does not == `Some(TRACE)`, it means
501        // something more like: "whatever all the other
502        // layers agree on, default to `TRACE` if none
503        // have an opinion". We also choose do this AFTER
504        // we check for per-layer filters, which
505        // have their own logic.
506        //
507        // Also note that this does come at some perf cost, but
508        // this function is only called on initialization and
509        // subscriber reloading.
510        if super::layer_is_none(&self.layer) {
511            return cmp::max(outer_hint, Some(inner_hint?));
512        }
513
514        // Similarly, if the layer on the inside is `None` and it returned an
515        // `Off` hint, we want to override that with the outer hint.
516        if inner_is_none && inner_hint == Some(LevelFilter::OFF) {
517            return outer_hint;
518        }
519
520        cmp::max(outer_hint, inner_hint)
521    }
522}
523
524impl<A, B, S> fmt::Debug for Layered<A, B, S>
525where
526    A: fmt::Debug,
527    B: fmt::Debug,
528{
529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530        #[cfg(all(feature = "registry", feature = "std"))]
531        let alt = f.alternate();
532        let mut s = f.debug_struct("Layered");
533        // These additional fields are more verbose and usually only necessary
534        // for internal debugging purposes, so only print them if alternate mode
535        // is enabled.
536
537        #[cfg(all(feature = "registry", feature = "std"))]
538        {
539            if alt {
540                s.field("inner_is_registry", &self.inner_is_registry)
541                    .field("has_layer_filter", &self.has_layer_filter)
542                    .field("inner_has_layer_filter", &self.inner_has_layer_filter);
543            }
544        }
545
546        s.field("layer", &self.layer)
547            .field("inner", &self.inner)
548            .finish()
549    }
550}