Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement subscribe::Filter for Option<Filter> #2407

Merged
merged 16 commits into from
Sep 28, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
99 changes: 99 additions & 0 deletions tracing-subscriber/src/filter/subscriber_filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,36 @@ macro_rules! filter_impl_body {
fn max_level_hint(&self) -> Option<LevelFilter> {
self.deref().max_level_hint()
}

#[inline]
fn event_enabled(&self, event: &Event<'_>, cx: &Context<'_, S>) -> bool {
self.deref().event_enabled(event, cx)
}

#[inline]
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
self.deref().on_new_span(attrs, id, ctx)
}

#[inline]
fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
self.deref().on_record(id, values, ctx)
}

#[inline]
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
self.deref().on_enter(id, ctx)
}

#[inline]
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
self.deref().on_exit(id, ctx)
}

#[inline]
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
self.deref().on_close(id, ctx)
}
};
}

Expand All @@ -493,6 +523,75 @@ impl<S> subscribe::Filter<S> for Box<dyn subscribe::Filter<S> + Send + Sync + 's
filter_impl_body!();
}

// Implement Filter for Option<Filter> where None => allow
#[cfg(feature = "registry")]
#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
impl<F, S> subscribe::Filter<S> for Option<F>
where
F: subscribe::Filter<S>,
{
#[inline]
fn enabled(&self, meta: &Metadata<'_>, ctx: &Context<'_, S>) -> bool {
self.as_ref()
.map(|inner| inner.enabled(meta, ctx))
.unwrap_or(true)
}

#[inline]
fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
self.as_ref()
.map(|inner| inner.callsite_enabled(meta))
.unwrap_or_else(Interest::sometimes)
}

#[inline]
fn max_level_hint(&self) -> Option<LevelFilter> {
self.as_ref().and_then(|inner| inner.max_level_hint())
}

#[inline]
fn event_enabled(&self, event: &Event<'_>, ctx: &Context<'_, S>) -> bool {
self.as_ref()
.map(|inner| inner.event_enabled(event, ctx))
.unwrap_or(true)
}

#[inline]
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
if let Some(inner) = self {
inner.on_new_span(attrs, id, ctx)
}
}

#[inline]
fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
if let Some(inner) = self {
inner.on_record(id, values, ctx)
}
}

#[inline]
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
if let Some(inner) = self {
inner.on_enter(id, ctx)
}
}

#[inline]
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
if let Some(inner) = self {
inner.on_exit(id, ctx)
}
}

#[inline]
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
if let Some(inner) = self {
inner.on_close(id, ctx)
}
}
}

// === impl Filtered ===

impl<S, F, C> Filtered<S, F, C> {
Expand Down
24 changes: 21 additions & 3 deletions tracing-subscriber/src/subscribe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,12 +464,30 @@
//!
//! This crate's [`filter`] module provides a number of types which implement
//! the [`Filter`] trait, such as [`LevelFilter`], [`Targets`], and
//! [`FilterFn`]. These [`Filter`]s provide ready-made implementations of
//! common forms of filtering. For custom filtering policies, the [`FilterFn`]
//! and [`DynFilterFn`] types allow implementing a [`Filter`] with a closure or
//! [`FilterFn`]. These [`Filter`]s provide ready-made implementations of common
//! forms of filtering. For custom filtering policies, the [`FilterFn`] and
//! [`DynFilterFn`] types allow implementing a [`Filter`] with a closure or
//! function pointer. In addition, when more control is required, the [`Filter`]
//! trait may also be implemented for user-defined types.
//!
//! [`Option<Filter>`] also implements [`Filter`], which allows for an optional
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit, not a blocker: it could be nice to link to the implementation of Filter for Option<Filter> in the docs here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the rustdoc syntax to link to a trait implementation?

//! filter. [`None`](Option::None) filters out _nothing_ (that is, allows
//! everything through). For example:
//!
//! ```rust
//! # use tracing_subscriber::{filter::filter_fn, Subscribe};
//! # use tracing_core::{Metadata, collect::Collect};
//! # struct MySubscriber<C>(std::marker::PhantomData<C>);
//! # impl<C> MySubscriber<C> { fn new() -> Self { Self(std::marker::PhantomData)} }
//! # impl<C: Collect> Subscribe<C> for MySubscriber<C> {}
//! # fn my_filter(_: &str) -> impl Fn(&Metadata) -> bool { |_| true }
//! fn setup_tracing<C: Collect>(filter_config: Option<&str>) {
//! let layer = MySubscriber::<C>::new()
//! .with_filter(filter_config.map(|config| filter_fn(my_filter(config))));
//! //...
//! }
//! ```
//!
//! <div class="example-wrap" style="display:inline-block">
//! <pre class="compile_fail" style="white-space:normal;font:inherit;">
//! <strong>Warning</strong>: Currently, the <a href="../struct.Registry.html">
Expand Down
1 change: 1 addition & 0 deletions tracing-subscriber/tests/subscriber_filters/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![cfg(feature = "registry")]
mod filter_scopes;
mod option;
mod per_event;
mod targets;
mod trees;
Expand Down
60 changes: 60 additions & 0 deletions tracing-subscriber/tests/subscriber_filters/option.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use super::*;
use tracing_subscriber::{filter, prelude::*, Subscribe};

fn filter_out_everything<S>() -> filter::DynFilterFn<S> {
// Use dynamic filter fn to disable interest caching and max-level hints,
// allowing us to put all of these tests in the same file.
filter::dynamic_filter_fn(|_, _| false)
}

#[test]
fn option_some() {
let (subscribe, handle) = subscriber::mock().only().run_with_handle();
let subscribe = subscribe.with_filter(Some(filter_out_everything()));

let _guard = tracing_subscriber::registry().with(subscribe).set_default();

for i in 0..2 {
tracing::info!(i);
}

handle.assert_finished();
}

#[test]
fn option_none() {
let (subscribe, handle) = subscriber::mock()
.event(expect::event())
.event(expect::event())
.only()
.run_with_handle();
let subscribe = subscribe.with_filter(None::<filter::DynFilterFn<_>>);

let _guard = tracing_subscriber::registry().with(subscribe).set_default();

for i in 0..2 {
tracing::info!(i);
}

handle.assert_finished();
}

#[test]
fn option_mixed() {
let (subscribe, handle) = subscriber::mock()
.event(expect::event())
.only()
.run_with_handle();
let subscribe = subscribe
.with_filter(filter::dynamic_filter_fn(|meta, _ctx| {
meta.target() == "interesting"
}))
.with_filter(None::<filter::DynFilterFn<_>>);
Comment on lines +49 to +57
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is worth having, but the scenario i really wanted to test was not a single subscriber with two different filters, but two different subscribers with separate filters, where one subscriber's filter was a None. in particular, we want to assert that the None filter does not inadvertantly enable anything that the other subscriber's filter would enable.

we also really want to test that the correct max level hint is used, since that's something we've had bugs with in the past.


let _guard = tracing_subscriber::registry().with(subscribe).set_default();

tracing::info!(target: "interesting", x="foo");
tracing::info!(target: "boring", x="bar");

handle.assert_finished();
}