Struct tracing_subscriber::filter::targets::Targets

source ·
pub struct Targets(/* private fields */);
Expand description

A filter that enables or disables spans and events based on their target and level.

Targets are typically equal to the Rust module path of the code where the span or event was recorded, although they may be overridden.

This type 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.

§Filtering With Targets

A Targets filter consists of one or more target prefixes, paired with LevelFilters. If a span or event’s target begins with one of those prefixes, and its level is at or below the LevelFilter enabled for that prefix, then the span or event will be enabled.

This is similar to the behavior implemented by the env_logger crate in the log ecosystem.

The EnvFilter type also provided by this crate is very similar to Targets, but is capable of a more sophisticated form of filtering where events may also be enabled or disabled based on the span they are recorded in. Targets can be thought of as a lighter-weight form of EnvFilter that can be used instead when this dynamic filtering is not required.

§Examples

A Targets filter can be constructed by programmatically adding targets and levels to enable:

use tracing_subscriber::{filter, prelude::*};
use tracing_core::Level;

let filter = filter::Targets::new()
    // Enable the `INFO` level for anything in `my_crate`
    .with_target("my_crate", Level::INFO)
    // Enable the `DEBUG` level for a specific module.
    .with_target("my_crate::interesting_module", Level::DEBUG);

// Build a new subscriber with the `fmt` layer using the `Targets`
// filter we constructed above.
tracing_subscriber::registry()
    .with(tracing_subscriber::fmt::layer())
    .with(filter)
    .init();

LevelFilter::OFF can be used to disable a particular target:

use tracing_subscriber::filter::{Targets, LevelFilter};
use tracing_core::Level;

let filter = Targets::new()
    .with_target("my_crate", Level::INFO)
    // Disable all traces from `annoying_module`.
    .with_target("my_crate::annoying_module", LevelFilter::OFF);

Alternatively, Targets implements std::str::FromStr, allowing it to be parsed from a comma-delimited list of target=level pairs. For example:

use tracing_subscriber::filter;
use tracing_core::Level;

let filter = "my_crate=info,my_crate::interesting_module=trace,other_crate=debug"
    .parse::<filter::Targets>()?;

// The parsed filter is identical to a filter constructed using `with_target`:
assert_eq!(
    filter,
    filter::Targets::new()
        .with_target("my_crate", Level::INFO)
        .with_target("my_crate::interesting_module", Level::TRACE)
        .with_target("other_crate", Level::DEBUG)
);

This is particularly useful when the list of enabled targets is configurable by the user at runtime.

The Targets filter can be used as a per-layer filter and as a global filter:

use tracing_subscriber::{
    fmt,
    filter::{Targets, LevelFilter},
    prelude::*,
};
use tracing_core::Level;
use std::{sync::Arc, fs::File};

// A layer that logs events to stdout using the human-readable "pretty"
// format.
let stdout_log = fmt::layer().pretty();

// A layer that logs events to a file, using the JSON format.
let file = File::create("debug_log.json")?;
let debug_log = fmt::layer()
    .with_writer(Arc::new(file))
    .json();

tracing_subscriber::registry()
    // Only log INFO and above to stdout, unless the span or event
    // has the `my_crate::cool_module` target prefix.
    .with(stdout_log
        .with_filter(
            Targets::default()
                .with_target("my_crate::cool_module", Level::DEBUG)
                .with_default(Level::INFO)
       )
    )
    // Log everything enabled by the global filter to `debug_log.json`.
    .with(debug_log)
    // Configure a global filter for the whole subscriber stack. This will
    // control what spans and events are recorded by both the `debug_log`
    // and the `stdout_log` layers, and `stdout_log` will *additionally* be
    // filtered by its per-layer filter.
    .with(
        Targets::default()
            .with_target("my_crate", Level::TRACE)
            .with_target("other_crate", Level::INFO)
            .with_target("other_crate::annoying_module", LevelFilter::OFF)
            .with_target("third_crate", Level::DEBUG)
    ).init();

Implementations§

source§

impl Targets

source

pub fn new() -> Self

Returns a new Targets filter.

This filter will enable no targets. Call with_target or with_targets to add enabled targets, and with_default to change the default level enabled for spans and events that didn’t match any of the provided targets.

source

pub fn with_target( self, target: impl Into<String>, level: impl Into<LevelFilter> ) -> Self

Enables spans and events with targets starting with the provided target prefix if they are at or below the provided LevelFilter.

§Examples
use tracing_subscriber::filter;
use tracing_core::Level;

let filter = filter::Targets::new()
    // Enable the `INFO` level for anything in `my_crate`
    .with_target("my_crate", Level::INFO)
    // Enable the `DEBUG` level for a specific module.
    .with_target("my_crate::interesting_module", Level::DEBUG);

LevelFilter::OFF can be used to disable a particular target:

use tracing_subscriber::filter::{Targets, LevelFilter};
use tracing_core::Level;

let filter = Targets::new()
    .with_target("my_crate", Level::INFO)
    // Disable all traces from `annoying_module`.
    .with_target("my_crate::interesting_module", LevelFilter::OFF);
source

pub fn with_targets<T, L>( self, targets: impl IntoIterator<Item = (T, L)> ) -> Self
where String: From<T>, LevelFilter: From<L>,

Adds targets from an iterator of target-LevelFilter pairs to this filter.

§Examples
use tracing_subscriber::filter;
use tracing_core::Level;

let filter = filter::Targets::new()
    .with_targets(vec![
        ("my_crate", Level::INFO),
        ("my_crate::some_module", Level::DEBUG),
        ("my_crate::other_module::cool_stuff", Level::TRACE),
        ("other_crate", Level::WARN)
    ]);

LevelFilter::OFF can be used to disable a particular target:

use tracing_subscriber::filter::{Targets, LevelFilter};
use tracing_core::Level;

let filter = Targets::new()
    .with_target("my_crate", Level::INFO)
    // Disable all traces from `annoying_module`.
    .with_target("my_crate::interesting_module", LevelFilter::OFF);
source

pub fn with_default(self, level: impl Into<LevelFilter>) -> Self

Sets the default level to enable for spans and events whose targets did not match any of the configured prefixes.

By default, this is LevelFilter::OFF. This means that spans and events will only be enabled if they match one of the configured target prefixes. If this is changed to a different LevelFilter, spans and events with targets that did not match any of the configured prefixes will be enabled if their level is at or below the provided level.

source

pub fn default_level(&self) -> Option<LevelFilter>

Returns the default level for this filter, if one is set.

The default level is used to filter any spans or events with targets that do not match any of the configured set of prefixes.

The default level can be set for a filter either by using with_default or when parsing from a filter string that includes a level without a target (e.g. "trace").

§Examples
use tracing_subscriber::filter::{LevelFilter, Targets};

let filter = Targets::new().with_default(LevelFilter::INFO);
assert_eq!(filter.default_level(), Some(LevelFilter::INFO));

let filter: Targets = "info".parse().unwrap();
assert_eq!(filter.default_level(), Some(LevelFilter::INFO));

The default level is None if no default is set:

use tracing_subscriber::filter::Targets;

let filter = Targets::new();
assert_eq!(filter.default_level(), None);

let filter: Targets = "my_crate=info".parse().unwrap();
assert_eq!(filter.default_level(), None);

Note that an unset default level (None) behaves like LevelFilter::OFF when the filter is used, but it could also be set explicitly which may be useful to distinguish (such as when merging multiple Targets).

use tracing_subscriber::filter::{LevelFilter, Targets};

let filter = Targets::new().with_default(LevelFilter::OFF);
assert_eq!(filter.default_level(), Some(LevelFilter::OFF));

let filter: Targets = "off".parse().unwrap();
assert_eq!(filter.default_level(), Some(LevelFilter::OFF));
source

pub fn iter(&self) -> Iter<'_>

Returns an iterator over the target-LevelFilter pairs in this filter.

The order of iteration is undefined.

§Examples
use tracing_subscriber::filter::{Targets, LevelFilter};
use tracing_core::Level;

let filter = Targets::new()
    .with_target("my_crate", Level::INFO)
    .with_target("my_crate::interesting_module", Level::DEBUG);

let mut targets: Vec<_> = filter.iter().collect();
targets.sort();

assert_eq!(targets, vec![
    ("my_crate", LevelFilter::INFO),
    ("my_crate::interesting_module", LevelFilter::DEBUG),
]);
source

pub fn would_enable(&self, target: &str, level: &Level) -> bool

Returns whether a target-Level pair would be enabled by this Targets.

This method can be used with module_path! from std as the target in order to emulate the behavior of the tracing::event! and tracing::span! macros.

§Examples
use tracing_subscriber::filter::{Targets, LevelFilter};
use tracing_core::Level;

let filter = Targets::new()
    .with_target("my_crate", Level::INFO)
    .with_target("my_crate::interesting_module", Level::DEBUG);

assert!(filter.would_enable("my_crate", &Level::INFO));
assert!(!filter.would_enable("my_crate::interesting_module", &Level::TRACE));

Trait Implementations§

source§

impl Clone for Targets

source§

fn clone(&self) -> Targets

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Targets

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Targets

source§

fn default() -> Targets

Returns the “default value” for a type. Read more
source§

impl Display for Targets

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T, L> Extend<(T, L)> for Targets
where T: Into<String>, L: Into<LevelFilter>,

source§

fn extend<I: IntoIterator<Item = (T, L)>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one #72631)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one #72631)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<S> Filter<S> for Targets

source§

fn enabled(&self, metadata: &Metadata<'_>, _: &Context<'_, S>) -> bool

Returns true if this layer is interested in a span or event with the given Metadata in the current Context, similarly to Subscriber::enabled. Read more
source§

fn callsite_enabled(&self, metadata: &'static Metadata<'static>) -> Interest

Returns an Interest indicating whether this layer will always, sometimes, or never be interested in the given Metadata. Read more
source§

fn max_level_hint(&self) -> Option<LevelFilter>

Returns an optional hint of the highest verbosity level that this Filter will enable. Read more
source§

fn event_enabled(&self, event: &Event<'_>, cx: &Context<'_, S>) -> bool

Called before the filtered [Layer]'s [on_event], to determine if on_event` should be called. Read more
source§

fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>)

Notifies this filter that a new span was constructed with the given Attributes and Id. Read more
source§

fn on_record(&self, id: &Id, values: &Record<'_>, ctx: Context<'_, S>)

Notifies this filter that a span with the given Id recorded the given values. Read more
source§

fn on_enter(&self, id: &Id, ctx: Context<'_, S>)

Notifies this filter that a span with the given ID was entered. Read more
source§

fn on_exit(&self, id: &Id, ctx: Context<'_, S>)

Notifies this filter that a span with the given ID was exited. Read more
source§

fn on_close(&self, id: Id, ctx: Context<'_, S>)

Notifies this filter that a span with the given ID has been closed. Read more
source§

impl<T, L> FromIterator<(T, L)> for Targets
where T: Into<String>, L: Into<LevelFilter>,

source§

fn from_iter<I: IntoIterator<Item = (T, L)>>(iter: I) -> Self

Creates a value from an iterator. Read more
source§

impl FromStr for Targets

§

type Err = ParseError

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
source§

impl<'a> IntoIterator for &'a Targets

§

type Item = (&'a str, LevelFilter)

The type of the elements being iterated over.
§

type IntoIter = Iter<'a>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl IntoIterator for Targets

§

type Item = (String, LevelFilter)

The type of the elements being iterated over.
§

type IntoIter = IntoIter

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<S> Layer<S> for Targets
where S: Subscriber,

source§

fn enabled(&self, metadata: &Metadata<'_>, _: Context<'_, S>) -> bool

Returns true if this layer is interested in a span or event with the given metadata in the current Context, similarly to Subscriber::enabled. Read more
source§

fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest

Registers a new callsite with this layer, returning whether or not the layer is interested in being notified about the callsite, similarly to Subscriber::register_callsite. Read more
source§

fn on_register_dispatch(&self, subscriber: &Dispatch)

Performs late initialization when installing this layer as a Subscriber. Read more
source§

fn on_layer(&mut self, subscriber: &mut S)

Performs late initialization when attaching a Layer to a Subscriber. Read more
source§

fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>)

Notifies this layer that a new span was constructed with the given Attributes and Id.
source§

fn on_record(&self, _span: &Id, _values: &Record<'_>, _ctx: Context<'_, S>)

Notifies this layer that a span with the given Id recorded the given values.
source§

fn on_follows_from(&self, _span: &Id, _follows: &Id, _ctx: Context<'_, S>)

Notifies this layer that a span with the ID span recorded that it follows from the span with the ID follows.
source§

fn event_enabled(&self, _event: &Event<'_>, _ctx: Context<'_, S>) -> bool

Called before on_event, to determine if on_event should be called.
source§

fn on_event(&self, _event: &Event<'_>, _ctx: Context<'_, S>)

Notifies this layer that an event has occurred.
source§

fn on_enter(&self, _id: &Id, _ctx: Context<'_, S>)

Notifies this layer that a span with the given ID was entered.
source§

fn on_exit(&self, _id: &Id, _ctx: Context<'_, S>)

Notifies this layer that the span with the given ID was exited.
source§

fn on_close(&self, _id: Id, _ctx: Context<'_, S>)

Notifies this layer that the span with the given ID has been closed.
source§

fn on_id_change(&self, _old: &Id, _new: &Id, _ctx: Context<'_, S>)

Notifies this layer that a span ID has been cloned, and that the subscriber returned a different ID.
source§

fn and_then<L>(self, layer: L) -> Layered<L, Self, S>
where L: Layer<S>, Self: Sized,

Composes this layer around the given Layer, returning a Layered struct implementing Layer. Read more
source§

fn with_subscriber(self, inner: S) -> Layered<Self, S>
where Self: Sized,

Composes this Layer with the given Subscriber, returning a Layered struct that implements Subscriber. Read more
source§

fn with_filter<F>(self, filter: F) -> Filtered<Self, F, S>
where Self: Sized, F: Filter<S>,

Combines self with a Filter, returning a Filtered layer. Read more
source§

fn boxed(self) -> Box<dyn Layer<S> + Send + Sync + 'static>
where Self: Sized + Layer<S> + Send + Sync + 'static, S: Subscriber,

Erases the type of this Layer, returning a Boxed dyn Layer trait object. Read more
source§

impl PartialEq for Targets

source§

fn eq(&self, other: &Targets) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl StructuralPartialEq for Targets

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<F, S> FilterExt<S> for F
where F: Filter<S>,

source§

fn and<B>(self, other: B) -> And<Self, B, S>
where Self: Sized, B: Filter<S>,

Combines this Filter with another Filter s so that spans and events are enabled if and only if both filters return true. Read more
source§

fn or<B>(self, other: B) -> Or<Self, B, S>
where Self: Sized, B: Filter<S>,

Combines two Filters so that spans and events are enabled if either filter returns true. Read more
source§

fn not(self) -> Not<Self, S>
where Self: Sized,

Inverts self, returning a filter that enables spans and events only if self would not enable them. Read more
source§

fn boxed(self) -> Box<dyn Filter<S> + Send + Sync + 'static>
where Self: Sized + Send + Sync + 'static,

Boxes self, erasing its concrete type. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more