🛈 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

Function dynamic_filter_fn

Source
pub fn dynamic_filter_fn<C, F>(f: F) -> DynFilterFn<C, F> 
where F: Fn(&Metadata<'_>, &Context<'_, C>) -> bool,
Expand description

Constructs a DynFilterFn from a function or closure that returns true if a span or event should be enabled within a particular span context.

This is equivalent to calling DynFilterFn::new.

Unlike filter_fn, this function takes a closure or function pointer taking the Metadata for a span or event and the current Context. This means that a DynFilterFn can choose whether to enable spans or events based on information about the current span (or its parents).

If this is not necessary, use filter_fn instead.

The returned DynFilterFn can be used for both per-subscriber filtering (using its Filter implementation) and global filtering (using its Subscribe implementation).

See the documentation on filtering with subscribers for details.

§Examples

use tracing_subscriber::{
    subscribe::{Subscribe, CollectExt},
    filter,
    util::SubscriberInitExt,
};

// Only enable spans or events within a span named "interesting_span".
let my_filter = filter::dynamic_filter_fn(|metadata, cx| {
    // If this *is* "interesting_span", make sure to enable it.
    if metadata.is_span() && metadata.name() == "interesting_span" {
        return true;
    }

    // Otherwise, are we in an interesting span?
    if let Some(current_span) = cx.lookup_current() {
        return current_span.name() == "interesting_span";
    }

    false
});

let my_subscriber = tracing_subscriber::fmt::subscriber();

tracing_subscriber::registry()
    .with(my_subscriber.with_filter(my_filter))
    .init();

// This event will not be enabled.
tracing::info!("something happened");

tracing::info_span!("interesting_span").in_scope(|| {
    // This event will be enabled.
    tracing::debug!("something else happened");
});