🛈 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

Struct EnvFilter

Source
pub struct EnvFilter { /* private fields */ }
Available on crate features env-filter and std only.
Expand description

A Subscriber which filters spans and events based on a set of filter directives.

EnvFilter implements both the Subscribe and Filter traits, so it may be used for both global filtering and per-subscriber filtering, respectively. See the documentation on filtering with Subscribers for details.

The Targets type implements a similar form of filtering, but without the ability to dynamically enable events based on the current span context, and without filtering on field values. When these features are not required, Targets provides a lighter-weight alternative to EnvFilter.

§Directives

A filter consists of one or more comma-separated directives which match on Spans and Events. Each directive may have a corresponding maximum verbosity level which enables (e.g., selects for) spans and events that match. Like log, tracing considers less exclusive levels (like trace or info) to be more verbose than more exclusive levels (like error or warn).

The directive syntax is similar to that of env_logger’s. At a high level, the syntax for directives consists of several parts:

target[span{field=value}]=level

Each component (target, span, field, value, and level) will be covered in turn.

  • target matches the event or span’s target. In general, this is the module path and/or crate name. Examples of targets h2, tokio::net, or tide::server. For more information on targets, please refer to Metadata’s documentation.
  • span matches on the span’s name. If a span directive is provided alongside a target, the span directive will match on spans within the target.
  • field matches on fields within spans. Field names can also be supplied without a value and will match on any Span or Event that has a field with that name. For example: [span{field=\"value\"}]=debug, [{field}]=trace.
  • value matches on the value of a span’s field. If a value is a numeric literal or a bool, it will match only on that value. Otherwise, this filter matches the std::fmt::Debug output from the value.
  • level sets a maximum verbosity level accepted by this directive.

When a field value directive ([{<FIELD NAME>=<FIELD_VALUE>}]=...) matches a value’s std::fmt::Debug output (i.e., the field value in the directive is not a bool, i64, u64, or f64 literal), the matched pattern may be interpreted as either a regular expression or as the precise expected output of the field’s std::fmt::Debug implementation. By default, these filters are interpreted as regular expressions, but this can be disabled using the Builder::with_regex builder method to use precise matching instead.

When field value filters are interpreted as regular expressions, the [regex-automata crate’s regular expression syntax][re-syntax] is supported.

Note: When filters are constructed from potentially untrusted inputs, disabling regular expression matching is strongly recommended.

§Usage Notes

  • The portion of the directive which is included within the square brackets is tracing-specific.
  • Any portion of the directive can be omitted.
    • The sole exception are the field and value directives. If a value is provided, a field must also be provided. However, the converse does not hold, as fields can be matched without a value.
  • If only a level is provided, it will set the maximum level for all Spans and Events that are not enabled by other filters.
  • A directive without a level will enable anything that it matches. This is equivalent to =trace.
  • When a crate has a dash in its name, the default target for events will be the crate’s module path as it appears in Rust. This means every dash will be replaced with an underscore.
  • A dash in a target will only appear when being specified explicitly: tracing::info!(target: "target-name", ...);

§Example Syntax

  • tokio::net=info will enable all spans or events that:
    • have the tokio::net target,
    • at the level info or above.
  • warn,tokio::net=info will enable all spans and events that:
    • are at the level warn or above, or
    • have the tokio::net target at the level info or above.
  • my_crate[span_a]=trace will enable all spans and events that:
    • are within the span_a span or named span_a if span_a has the target my_crate,
    • at the level trace or above.
  • [span_b{name=\"bob\"}] will enable all spans or event that:
    • have any target,
    • are inside a span named span_b,
    • which has a field named name with value bob,
    • at any level.

§Examples

Parsing an EnvFilter from the default environment variable (RUST_LOG):

use tracing_subscriber::{EnvFilter, fmt, prelude::*};

tracing_subscriber::registry()
    .with(fmt::subscriber())
    .with(EnvFilter::from_default_env())
    .init();

Parsing an EnvFilter from a user-provided environment variable:

use tracing_subscriber::{EnvFilter, fmt, prelude::*};

tracing_subscriber::registry()
    .with(fmt::subscriber())
    .with(EnvFilter::from_env("MYAPP_LOG"))
    .init();

Using EnvFilter as a per-subscriber filter to filter only a single subscriber:

use tracing_subscriber::{EnvFilter, fmt, prelude::*};

// Parse an `EnvFilter` configuration from the `RUST_LOG`
// environment variable.
let filter = EnvFilter::from_default_env();

// Apply the filter to this subscriber *only*.
let filtered_subscriber = fmt::subscriber().with_filter(filter);

// Some other subscriber, whose output we don't want to filter.
let unfiltered_subscriber = // ...

tracing_subscriber::registry()
    .with(filtered_subscriber)
    .with(unfiltered_subscriber)
    .init();

§Constructing EnvFilters

An EnvFilter is be constructed by parsing a string containing one or more directives. The EnvFilter::new constructor parses an EnvFilter from a string, ignoring any invalid directives, while EnvFilter::try_new returns an error if invalid directives are encountered. Similarly, the EnvFilter::from_env and EnvFilter::try_from_env constructors parse an EnvFilter from the value of the provided environment variable, with lossy and strict validation, respectively.

A builder interface is available to set additional configuration options prior to parsing an EnvFilter. See the Builder type’s documentation for details on the options that can be configured using the builder.

Implementations§

Source§

impl EnvFilter

Source

pub const DEFAULT_ENV: &'static str = "RUST_LOG"

RUST_LOG is the default environment variable used by EnvFilter::from_default_env and EnvFilter::try_from_default_env.

Source

pub fn builder() -> Builder

Returns a builder that can be used to configure a new EnvFilter instance.

The Builder type is used to set additional configurations, such as whether regular expressions are enabled or the default directive before parsing an EnvFilter from a string or environment variable.

Source

pub fn from_default_env() -> Self

Returns a new EnvFilter from the value of the RUST_LOG environment variable, ignoring any invalid filter directives.

If the environment variable is empty or not set, or if it contains only invalid directives, a default directive enabling the ERROR level is added.

To set additional configuration options prior to parsing the filter, use the Builder type instead.

This function is equivalent to the following:

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

EnvFilter::builder()
    .with_default_directive(LevelFilter::ERROR.into())
    .from_env_lossy()
Source

pub fn from_env<A: AsRef<str>>(env: A) -> Self

Returns a new EnvFilter from the value of the given environment variable, ignoring any invalid filter directives.

If the environment variable is empty or not set, or if it contains only invalid directives, a default directive enabling the ERROR level is added.

To set additional configuration options prior to parsing the filter, use the Builder type instead.

This function is equivalent to the following:

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

EnvFilter::builder()
    .with_default_directive(LevelFilter::ERROR.into())
    .with_env_var(env)
    .from_env_lossy()
Source

pub fn new<S: AsRef<str>>(directives: S) -> Self

Returns a new EnvFilter from the directives in the given string, ignoring any that are invalid.

If the string is empty or contains only invalid directives, a default directive enabling the ERROR level is added.

To set additional configuration options prior to parsing the filter, use the Builder type instead.

This function is equivalent to the following:

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

EnvFilter::builder()
    .with_default_directive(LevelFilter::ERROR.into())
    .parse_lossy(directives)
Source

pub fn try_new<S: AsRef<str>>(dirs: S) -> Result<Self, ParseError>

Returns a new EnvFilter from the directives in the given string, or an error if any are invalid.

If the string is empty, a default directive enabling the ERROR level is added.

To set additional configuration options prior to parsing the filter, use the Builder type instead.

This function is equivalent to the following:

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

EnvFilter::builder()
    .with_default_directive(LevelFilter::ERROR.into())
    .parse(directives)
Source

pub fn try_from_default_env() -> Result<Self, FromEnvError>

Returns a new EnvFilter from the value of the RUST_LOG environment variable, or an error if the environment variable is unset or contains any invalid filter directives.

To set additional configuration options prior to parsing the filter, use the Builder type instead.

This function is equivalent to the following:

use tracing_subscriber::EnvFilter;

EnvFilter::builder().try_from_env()
Source

pub fn try_from_env<A: AsRef<str>>(env: A) -> Result<Self, FromEnvError>

Returns a new EnvFilter from the value of the given environment variable, or an error if the environment variable is unset or contains any invalid filter directives.

To set additional configuration options prior to parsing the filter, use the Builder type instead.

This function is equivalent to the following:

use tracing_subscriber::EnvFilter;

EnvFilter::builder().with_env_var(env).try_from_env()
Source

pub fn add_directive(self, directive: Directive) -> Self

Add a filtering directive to this EnvFilter.

The added directive will be used in addition to any previously set directives, either added using this method or provided when the filter is constructed.

Filters may be created from LevelFilter or Level, which will enable all traces at or below a certain verbosity level, or parsed from a string specifying a directive.

If a filter directive is inserted that matches exactly the same spans and events as a previous filter, but sets a different level for those spans and events, the previous directive is overwritten.

§Examples

From LevelFilter:

use tracing_subscriber::filter::{EnvFilter, LevelFilter};
let mut filter = EnvFilter::from_default_env()
    .add_directive(LevelFilter::INFO.into());

Or from Level:

let mut filter = EnvFilter::from_default_env()
    .add_directive(Level::INFO.into());

Parsed from a string:

use tracing_subscriber::filter::{EnvFilter, Directive};

let mut filter = EnvFilter::try_from_default_env()?
    .add_directive("my_crate::module=trace".parse()?)
    .add_directive("my_crate::my_other_module::something=info".parse()?);

In the above example, substitute my_crate, module, etc. with the name your target crate/module is imported with. This might be different from the package name in Cargo.toml (- is replaced by _). Example, if the package name in your Cargo.toml is MY-FANCY-LIB, then the corresponding Rust identifier would be MY_FANCY_LIB:

Source

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

Returns true if this EnvFilter would enable the provided metadata in the current context.

This is equivalent to calling the Subscribe::enabled or Filter::enabled methods on EnvFilter’s implementations of those traits, but it does not require the trait to be in scope.

Source

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

Returns an optional hint of the highest verbosity level that this EnvFilter will enable.

This is equivalent to calling the Subscribe::max_level_hint or Filter::max_level_hint methods on EnvFilter’s implementations of those traits, but it does not require the trait to be in scope.

Source

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

Informs the filter that a new span was created.

This is equivalent to calling the Subscribe::on_new_span or Filter::on_new_span methods on EnvFilter’s implementations of those traits, but it does not require the trait to be in scope.

Source

pub fn on_enter<C>(&self, id: &Id, _: Context<'_, C>)

Informs the filter that the span with the provided id was entered.

This is equivalent to calling the Subscribe::on_enter or Filter::on_enter methods on EnvFilter’s implementations of those traits, but it does not require the trait to be in scope.

Source

pub fn on_exit<C>(&self, id: &Id, _: Context<'_, C>)

Informs the filter that the span with the provided id was exited.

This is equivalent to calling the Subscribe::on_exit or Filter::on_exit methods on EnvFilter’s implementations of those traits, but it does not require the trait to be in scope.

Source

pub fn on_close<C>(&self, id: Id, _: Context<'_, C>)

Informs the filter that the span with the provided id was closed.

This is equivalent to calling the Subscribe::on_close or Filter::on_close methods on EnvFilter’s implementations of those traits, but it does not require the trait to be in scope.

Source

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

Informs the filter that the span with the provided id recorded the provided field values.

This is equivalent to calling the Subscribe::on_record or Filter::on_record methods on EnvFilter’s implementations of those traits, but it does not require the trait to be in scope

Trait Implementations§

Source§

impl Debug for EnvFilter

Source§

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

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

impl Default for EnvFilter

Source§

fn default() -> Self

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

impl Display for EnvFilter

Source§

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

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

impl<C> Filter<C> for EnvFilter

Available on crate feature registry only.
Source§

fn enabled(&self, meta: &Metadata<'_>, ctx: &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 callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest

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>

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

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

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<'_, C>)

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<'_, C>)

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

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

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

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

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

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

Called before the filtered subscribers’ on_event, to determine if on_event should be called. Read more
Source§

impl<S> From<S> for EnvFilter
where S: AsRef<str>,

Source§

fn from(s: S) -> Self

Converts to this type from the input type.
Source§

impl FromStr for EnvFilter

Source§

type Err = ParseError

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

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

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

impl<C: Collect> Subscribe<C> for EnvFilter

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 enabled(&self, metadata: &Metadata<'_>, ctx: 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 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, id: &Id, values: &Record<'_>, ctx: Context<'_, C>)

Notifies this subscriber that a span with the given Id recorded the given values.
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_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_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_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 feature registry 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

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

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

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