tracing_filter/
layer.rs

1use {
2    crate::Filter,
3    tracing_core::{span, Event, Interest, LevelFilter, Metadata, Subscriber},
4    tracing_subscriber::layer::{Context, Layer},
5};
6
7// FUTURE: make this work for serialized events (e.g. tracing-memory). this will
8//         likely be a huge chunk of work of its own, because it effectively
9//         means designing the serialization format in order to abstract over it
10//         and the tracing context / subscriber registry storage implementation.
11//         Also: not using the upstream Filter trait anymore.
12
13/// A [`Layer`] which elevates a [`Filter`] from applying to a single
14/// subscriber to the entire layered subscribe stack.
15pub struct FilterLayer<F> {
16    filter: F,
17}
18
19impl<F> FilterLayer<F> {
20    /// Create a new filter layer using the provided filter.
21    pub fn new(filter: F) -> Self {
22        Self { filter }
23    }
24}
25
26impl<S: Subscriber, F: 'static + Filter<S>> Layer<S> for FilterLayer<F> {
27    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
28        self.filter.callsite_enabled(metadata)
29    }
30
31    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
32        self.filter.enabled(metadata, &ctx)
33    }
34
35    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
36        self.filter.on_new_span(attrs, id, ctx);
37    }
38
39    fn max_level_hint(&self) -> Option<LevelFilter> {
40        self.filter.max_level_hint()
41    }
42
43    fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
44        self.filter.on_record(id, values, ctx)
45    }
46
47    fn on_event(&self, _event: &Event<'_>, _ctx: Context<'_, S>) {
48        // FUTURE: allow event filtering; tokio-rs/tracing#2008
49    }
50
51    fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
52        self.filter.on_enter(id, ctx)
53    }
54
55    fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
56        self.filter.on_exit(id, ctx)
57    }
58
59    fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
60        self.filter.on_close(id, ctx)
61    }
62}