Skip to content

Commit 09374e5

Browse files
guswynnhawkw
authored andcommitted
subscriber: add Targets::would_enable (#1903
## Motivation As discussed on discord, this API + `Targets` being `: Clone` makes it easier to solve the original problem I had tried to solve in #1889. My plan on how to use this is in https://github.com/MaterializeInc/materialize/issues/10441 if you are interested! ## Solution I considered doing some macro magic to create a `Metadata` with a callsite and empty fields and everything, to be able to called `DirectiveSet::enabled`, but it felt cleaner and easier to reason about the special-case-ness (`Targets` never having field filters) using a new set of methods that do a similar thing. For testing I opted for just a doc-test, let me know if thats fine!
1 parent 77ddb0a commit 09374e5

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

tracing-subscriber/src/filter/targets.rs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use core::{
2020
slice,
2121
str::FromStr,
2222
};
23-
use tracing_core::{Collect, Interest, Metadata};
23+
use tracing_core::{Collect, Interest, Level, Metadata};
2424

2525
/// A filter that enables or disables spans and events based on their [target]
2626
/// and [level].
@@ -313,6 +313,35 @@ impl Targets {
313313
Interest::never()
314314
}
315315
}
316+
317+
/// Returns whether a [target]-[`Level`] pair would be enabled
318+
/// by this `Targets`.
319+
///
320+
/// This method can be used with [`module_path!`] from `std` as the target
321+
/// in order to emulate the behavior of the [`tracing::event!`] and [`tracing::span!`]
322+
/// macros.
323+
///
324+
/// # Examples
325+
///
326+
/// ```
327+
/// use tracing_subscriber::filter::{Targets, LevelFilter};
328+
/// use tracing_core::Level;
329+
///
330+
/// let filter = Targets::new()
331+
/// .with_target("my_crate", Level::INFO)
332+
/// .with_target("my_crate::interesting_module", Level::DEBUG);
333+
///
334+
/// assert!(filter.would_enable("my_crate", &Level::INFO));
335+
/// assert!(!filter.would_enable("my_crate::interesting_module", &Level::TRACE));
336+
/// ```
337+
///
338+
/// [target]: tracing_core::Metadata::target
339+
/// [`module_path!`]: std::module_path!
340+
pub fn would_enable(&self, target: &str, level: &Level) -> bool {
341+
// "Correct" to call because `Targets` only produces `StaticDirective`'s with NO
342+
// fields
343+
self.0.target_enabled(target, level)
344+
}
316345
}
317346

318347
impl<T, L> Extend<(T, L)> for Targets

0 commit comments

Comments
 (0)