๐Ÿ›ˆ 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::targets

Struct Targets

Source
pub struct Targets(/* private fields */);
Available on crate features std or alloc only.
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-subscriber filtering (using its Filter implementation) and global filtering (using its Subscribe implementation).

See the documentation on filtering with subscribers 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 collector with the `fmt` subscriber using the `Targets`
// filter we constructed above.
tracing_subscriber::registry()
    .with(tracing_subscriber::fmt::subscriber())
    .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-subscriber filter and as a global filter:

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

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

// A subscriber that logs events to a file, using the JSON format.
let file = File::create("debug_log.json")?;
let debug_log = fmt::subscriber()
    .with_writer(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` subscribers, and `stdout_log` will *additionally* be
    // filtered by its per-subscriber 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<C> Filter<C> for Targets

Available on crate feature registry only.
Sourceยง

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

Available on crate feature std only.
Returns true if this subscriber is interested in a span or event with the given Metadata in the current Context, similarly to Collect::enabled. Read more
Sourceยง

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

Available on crate feature std only.
Returns an Interest indicating whether this subscriber will always, sometimes, or never be interested in the given Metadata. Read more
Sourceยง

fn max_level_hint(&self) -> Option<LevelFilter> โ“˜

Available on crate feature std only.
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

Available on crate feature std only.
Called before the filtered subscribersโ€™ 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>)

Available on crate feature std only.
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>)

Available on crate feature std only.
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>)

Available on crate feature std only.
Notifies this filter that a span with the given ID was entered. Read more
Sourceยง

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

Available on crate feature std only.
Notifies this filter that a span with the given ID was exited. Read more
Sourceยง

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

Available on crate feature std only.
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

Sourceยง

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

Sourceยง

type Item = (&'a str, LevelFilter)

The type of the elements being iterated over.
Sourceยง

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

Sourceยง

type Item = (String, LevelFilter)

The type of the elements being iterated over.
Sourceยง

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 PartialEq for Targets

Sourceยง

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 ยท Sourceยง

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Sourceยง

impl<C> Subscribe<C> for Targets
where C: Collect,

Sourceยง

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

Returns true if this subscriber is interested in a span or event with the given metadata in the current Context, similarly to Collect::enabled. Read more
Sourceยง

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

Registers a new callsite with this subscriber, returning whether or not the subscriber is interested in being notified about the callsite, similarly to Collect::register_callsite. Read more
Sourceยง

fn on_register_dispatch(&self, collector: &Dispatch)

Performs late initialization when installing this subscriber as a collector. Read more
Sourceยง

fn on_subscribe(&mut self, collector: &mut C)

Performs late initialization when attaching a subscriber to a collector. Read more
Sourceยง

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

Notifies this subscriber that a new span was constructed with the given Attributes and Id.
Sourceยง

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

Notifies this subscriber that a span with the given Id recorded the given values.
Sourceยง

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

Notifies this subscriber 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<'_, C>) -> bool

Called before on_event, to determine if on_event should be called. Read more
Sourceยง

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

Notifies this subscriber that an event has occurred.
Sourceยง

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

Notifies this subscriber that a span with the given ID was entered.
Sourceยง

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

Notifies this subscriber that the span with the given ID was exited.
Sourceยง

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

Notifies this subscriber that the span with the given ID has been closed.
Sourceยง

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

Notifies this subscriber that a span ID has been cloned, and that the subscriber returned a different ID.
Sourceยง

fn and_then<S>(self, subscriber: S) -> Layered<S, Self, C> โ“˜
where S: Subscribe<C>, Self: Sized,

Composes this subscriber around the given collector, returning a Layered struct implementing Subscribe. Read more
Sourceยง

fn with_collector(self, inner: C) -> Layered<Self, C> โ“˜
where Self: Sized,

Composes this subscriber with the given collector, returning a Layered struct that implements Collect. Read more
Sourceยง

fn with_filter<F>(self, filter: F) -> Filtered<Self, F, C> โ“˜
where Self: Sized, F: Filter<C>,

Available on crate features registry and std only.
Combines self with a Filter, returning a Filtered subscriber. Read more
Sourceยง

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

Available on crate features alloc or std only.
Erases the type of this subscriber, returning a Boxed dyn Subscribe trait object. Read more
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<T> CloneToUninit for T
where T: Clone,

Sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut u8)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit #126799)
Performs copy-assignment from self to dst. 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>,

Available on crate features registry and std only.
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>,

Available on crate features registry and std only.
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,

Available on crate features registry and std only.
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,

Available on crate features registry and std only.
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,

Sourceยง

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ยง

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>,

Sourceยง

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>,

Sourceยง

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> WithCollector for T

Sourceยง

fn with_collector<C>(self, collector: C) -> WithDispatch<Self>
where C: Into<Dispatch>,

Attaches the provided collector to this type, returning a WithDispatch wrapper. Read more
Sourceยง

fn with_current_collector(self) -> WithDispatch<Self>

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