pub fn dynamic_filter_fn<S, F>(f: F) -> DynFilterFn<S, F>
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-layer filtering
(using its Filter
implementation) and global filtering (using
its Layer
implementation).
See the documentation on filtering with layers for details.
ยงExamples
use tracing_subscriber::{
layer::{Layer, SubscriberExt},
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_layer = tracing_subscriber::fmt::layer();
tracing_subscriber::registry()
.with(my_layer.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");
});