EnvFilter - filtering logs by target and level

Learn how EnvFilter reads directive strings, how target and level rules combine, how span filters work, and how to build a filter from code or the environment.

A subscriber with a single maximum level is a blunt tool. It shows everything up to one level and hides the rest, for every crate at once. EnvFilter replaces that single level with a list of rules called directives. Each directive names a target, a level, or both, and the filter checks every span and event against the list. This page teaches the directive language in full, because it is the language you will type into RUST_LOG for the rest of your Rust career.

Where This Fits

The subscriber decides which events become output, and a plain maximum level is its simplest decision rule. EnvFilter is the richer rule: a small program, written as a string, that the subscriber runs for every event. It is the piece that sits between the tracing macros and the formatter, and it is what makes per-crate debugging possible.

Think of it like a guest list at a door. A maximum level is a sign that says everyone at INFO or above may enter. An EnvFilter is a list with names on it: your own crate may enter at DEBUG, the noisy dependency may enter only at WARN, and everyone else follows the default rule. The door checks each arrival against the list, and the most specific matching entry wins.

The Smallest Working Version

This program builds an EnvFilter from a string and attaches it to the formatting subscriber.

# Cargo.toml
[package]
name = "filter_demo"
version = "0.1.0"
edition = "2021"

[dependencies]
tracing = "=0.1.44"
tracing-subscriber = { version = "=0.3.23", features = ["env-filter"] }
// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::new("info"))
        .init();
    tracing::trace!("trace event");
    tracing::debug!("debug event");
    tracing::info!("info event");
    tracing::warn!("warn event");
    tracing::error!("error event");
}

Running it prints exactly three lines.

2026-11-14T11:47:31.300750Z  INFO envfilter: info event
2026-11-14T11:47:31.300795Z  WARN envfilter: warn event
2026-11-14T11:47:31.300807Z ERROR envfilter: error event

The string "info" is a filter with one directive: a bare level, which sets the default maximum for everything. Trace and debug are hidden, and info, warn, and error pass. The env-filter feature in Cargo.toml is required, because EnvFilter and the .with_env_filter() method do not exist without it. The target in the output is the binary name, which is the module path of the code that emitted the event.

Three lines means the filter is working:

If you see the info, warn, and error lines and nothing else, the filter parsed your string and the subscriber is using it. A filter that fails to parse does not always shout about it, so this three-line check is worth doing the first time you write a filter string.

The Directive, Piece by Piece

A filter string is a comma-separated list of directives. Each directive has the same general shape.

target[span{field=value}]=level

Every part of that shape is optional except that a directive must contain something. The parts, from left to right, are the target, an optional span filter in square brackets, and an optional level after the equals sign. The sections below take each part on its own, because each part has its own rules and its own mistakes.

The level on its own

A bare level, with no target and no equals sign, sets the default maximum for everything that has no more specific rule.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::new("debug"))
        .init();
    tracing::debug!("debug is visible");
    tracing::trace!("trace is hidden");
}

The level names are the same five you already know, TRACE, DEBUG, INFO, WARN, and ERROR, plus one extra value, off, which disables everything it applies to. Level names are case-insensitive in a filter string: "INFO", "info", and "Debug" all parse to the same levels, which was verified by parsing each spelling and checking the resulting maximum. You can also write a level as a number from 0 to 5, where 0 means off and 5 means trace. "info" and "3" mean the same thing, but nobody writes the number in practice, and you should write the name so the next reader understands the string.

The target on its own

A target is the module path of the code that emitted the event. For your own crate, the target starts with the crate name, with hyphens turned into underscores. For a dependency, it starts with that dependency crate name. A bare target with no level means that target is enabled at TRACE, the most detailed level of all.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::new("warn,filter_demo"))
        .init();
    tracing::debug!("debug from your own crate");
    tracing::info!("info from your own crate");
}

The string "warn,filter_demo" has two directives. The first sets the default to WARN. The second names the target filter_demo with no level, which enables that target at TRACE. Both lines print, because the target rule is more specific than the default and wins for events from that target. A bare target is a quick way to turn one crate fully on while everything else stays quiet, and it is the form you reach for when you are debugging your own code and do not care about the exact level yet.

Target and level together

The most common directive pairs a target with a level, joined by an equals sign.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::new("filter_demo=debug"))
        .init();
    tracing::debug!("debug from your own crate");
    tracing::trace!("trace is still hidden");
}

The directive filter_demo=debug enables events from that target at DEBUG and above, and hides TRACE. A target in a directive is a prefix match: filter_demo=debug also matches the submodule filter_demo::handlers, because the submodule path starts with the target string. That prefix behaviour is what makes per-crate rules work without listing every module.

Two directives can name the same target at different depths, and the longest match wins. In the string "info,my_app=warn,my_app::db=debug", an event from my_app::db uses the DEBUG rule because my_app::db is longer than my_app, while an event from my_app::api uses the WARN rule. The filter always picks the most specific directive that matches, and falls back to the bare-level default only when nothing more specific matches.

Turning a target off

The level off disables a target completely, and it is most useful for silencing a noisy dependency while keeping your own logs.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::new("info,hyper=off"))
        .init();
    tracing::info!("your own info line");
}

The directive hyper=off disables every event whose target starts with hyper, while the bare info keeps everything else at INFO. This is the standard recipe for a chatty HTTP client or server crate that floods the terminal with DEBUG lines you did not ask for.

Be careful with the order of specificity here. The string "info,filter_demo=off" silences your own crate entirely, because the specific off rule wins over the general info rule for your own events. That was verified by running it: the program printed nothing at all. The off rule does what you asked, and what you asked was to turn your own crate off. Use off on dependencies, never on your own crate, unless you mean it.

The Span Part of a Directive

The square bracket part lets a directive match on the span an event happens inside, not just on where the event was written. The shape is target[span_name{field=value}]=level, and each piece inside the brackets narrows the match.

A directive with only a span name enables a higher level for events inside spans with that name.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::new("env2[checkout]=debug"))
        .init();
    let span = tracing::info_span!("checkout");
    let _guard = span.enter();
    tracing::debug!("debug inside checkout span");
    tracing::info!("info inside checkout span");
}

Running this prints both lines, each carrying the span context.

2026-11-14T11:47:58.391130Z DEBUG checkout: env2: debug inside checkout span
2026-11-14T11:47:58.391233Z  INFO checkout: env2: info inside checkout span

The default level here is off, because the string has no bare level and no other directive, so only events inside a span named checkout are enabled, and they are enabled at DEBUG. An event outside that span would print nothing.

Adding a field test narrows it further. The directive env2[checkout{user_id=42}]=debug enables DEBUG only for events inside a checkout span whose user_id field equals 42.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::new("info,env2[checkout{user_id=42}]=debug"))
        .init();
    let span = tracing::info_span!("checkout", user_id = 42);
    let _guard = span.enter();
    tracing::debug!("debug inside matching span");
    drop(_guard);
    let other = tracing::info_span!("checkout", user_id = 7);
    let _guard2 = other.enter();
    tracing::debug!("debug inside non-matching span");
}

Running this prints the first debug line and hides the second. The output was verified, and it shows the mechanism exactly: the matching span carries its context on the printed line, the non-matching span produces nothing at DEBUG, and the bare info directive still lets INFO and above through everywhere.

2026-11-14T11:47:58.382614Z DEBUG checkout{user_id=42}: env2: debug inside matching span

Span filters are how you debug one user, one request, or one job without turning DEBUG on for the whole program. They cost nothing when no matching span exists, because the filter check happens before any formatting work.

Span field values are matched as text:

The user_id=42 test compares the field value as it would be printed, so a numeric field and a string field with the same printed form match the same way. A field that the span does not have cannot match, and a span filter on a field that does not exist enables nothing.

How Directives Combine

When several directives match one event, the filter does not add them up or average them. It picks one winner, by these rules, in this order.

The longest matching target wins over a shorter one. my_app::db=debug beats my_app=warn for an event from my_app::db. A directive with a span filter beats one without a span filter when both match the same target, because the span test is more specific. A directive with a field test beats one with only a span name, for the same reason. When nothing specific matches, the bare level is the default, and when the string has no bare level at all, the default is off for targets with no matching directive, which is why the span-only example above printed nothing outside its span.

The maximum level hint of the whole filter is the most detailed level any directive allows. A filter built from "info,my_app=debug" reports a maximum of DEBUG, which was checked in a test. Tracing uses that hint to skip work for events more detailed than DEBUG before the filter even runs. That is an optimisation, not a rule you need to manage: the hint follows from the directives you wrote.

Building a Filter from Code

EnvFilter::new is the simplest constructor. It takes a string, parses it lossily, and never returns an error. Lossy means that a directive it cannot parse is silently dropped, and the rest of the string still works. That is convenient and dangerous at the same time, because a typo can silently remove the rule you meant to add.

EnvFilter::try_new is the strict version. It takes the same string and returns a result, so a bad directive becomes an error you can see.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    match EnvFilter::try_new("my_app=debg") {
        Ok(_) => println!("filter parsed"),
        Err(error) => println!("filter failed: {}", error),
    }
}

Running this prints the error in plain words.

filter failed: error parsing level filter: expected one of "off", "error", "warn", "info", "debug", "trace", or a number 0-5

The string "my_app=debg" fails because debg after the equals sign is not a level. The parser lists the values it accepts, which is the fastest way to spot a typo. Use try_new in code that builds a filter from a string you control, and handle the error by falling back to a safe default or by stopping with a message, never by ignoring it.

Two details of the parser are worth knowing because they surprise people. First, a bare word with no equals sign is always a target, never a level. The string "debg" parses successfully as a target named debg enabled at TRACE, which was verified in a test. That is why a typo in a bare level becomes a silent no-op instead of an error: the parser cannot tell that you meant a level. Second, spaces break parsing. The string "info, hyper = debug" fails, because the parser does not allow spaces around the equals sign or after the comma in that position. Write filter strings with no spaces at all.

EnvFilter::builder() is the third way to build a filter, and it adds a default directive that applies when the string has no bare level of its own.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    let filter = EnvFilter::builder()
        .with_default_directive(tracing::Level::INFO.into())
        .parse("filter_demo=debug")
        .unwrap();
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .init();
    tracing::debug!("debug from your own crate");
    tracing::info!("info from anywhere");
}

The builder sets INFO as the fallback, then parses the string for the specific rules. The program prints both lines: the debug line passes through the specific rule, and the info line passes through the default. The .parse() method on the builder returns a result, so a bad directive is an error here too. Use the builder when a filter string comes from outside your code and you want a guaranteed floor under it.

You can also extend a filter after building it with .add_directive(). The method takes the filter by value and returns a new one with the extra rule added.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    let filter = EnvFilter::new("info")
        .add_directive("my_app=debug".parse().unwrap());
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .init();
    tracing::debug!("debug from my_app");
}

The add_directive call consumes the filter and returns the extended one, so you assign the result back to the same variable name. This is the way to add a rule computed at runtime, such as a debug flag from a command-line argument, to a filter that started from a fixed string.

EnvFilter::new never tells you about a bad directive:

EnvFilter::new("my_app=debg") does not panic and does not return an error. It drops the bad directive and builds a filter from whatever is left. If that was the only directive, you get a filter that enables almost nothing, and your logs go silent. Prefer try_new or the builder when the string is written by hand.

Reading a Filter from the Environment

The most common source of a filter string is the RUST_LOG environment variable, and EnvFilter has constructors that read it directly. They come in pairs, one lossy and one strict, and the difference between them is what happens when the variable is missing or malformed.

EnvFilter::from_default_env() reads RUST_LOG, ignores any directives it cannot parse, and falls back to a filter that enables only ERROR when the variable is not set at all. EnvFilter::try_from_default_env() reads the same variable and returns an error when it is missing or malformed, so you can supply your own fallback.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    let filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new("info"));
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .init();
    tracing::info!("filter came from RUST_LOG, or info when it did not");
}

With no RUST_LOG set, this prints the info line, because the fallback supplies "info". With RUST_LOG=debug, it prints DEBUG and above. With RUST_LOG=debg, it prints nothing, because "debg" parses successfully as a target named debg, so try_from_default_env returns success with a filter that enables only that target, and the fallback never runs. That last case was verified by running the program, and it is the sharpest edge in this whole page: a typo that looks like a level is read as a target, and the fallback cannot save you. The environment variable itself, its recipes, and its traps have their own full treatment on the next page.

The from_env and try_from_env variants read a variable you name instead of RUST_LOG. EnvFilter::from_env("MY_APP_LOG") reads MY_APP_LOG with the same lossy behaviour, and try_from_env is its strict twin. Use a named variable when your program already has its own logging variable and you do not want to share RUST_LOG with every other Rust tool in the shell.

Attaching a Filter to a Subscriber

A filter is attached with .with_env_filter(...) on the formatting builder, or as a layer in a registry composition. The two forms do the same job, and the registry form is the one to use when the subscriber has more than one layer.

// src/main.rs
use tracing_subscriber::{fmt, EnvFilter, prelude::*};

fn main() {
    tracing_subscriber::registry()
        .with(fmt::layer().with_target(false))
        .with(EnvFilter::new("info"))
        .init();
    tracing::info!("registry with a filter layer");
}

The filter layer and the formatting layer are separate pieces. The filter decides, the formatter prints, and the registry holds them together. The prelude::* import brings the trait that makes .with() work.

One ordering rule matters when a builder has both a filter and a maximum level. The last call wins, because both calls write to the same filter slot on the builder. A builder with .with_env_filter(EnvFilter::new("info")) followed by .with_max_level(tracing::Level::ERROR) prints only errors. The same two calls in the opposite order prints INFO and above. This was verified by running both orders. Pick one of the two calls, not both, unless you mean the second one to replace the first.

Do not set both a filter and a maximum level on one builder:

The two calls fight over the same slot, and the later one silently replaces the earlier one. Your filter string is ignored without a warning when with_max_level comes after it. Use the filter for anything more specific than a single level, and leave with_max_level out.

Common Beginner Mistakes

Spaces in the filter string

// Wrong - spaces break parsing
let filter = EnvFilter::new("info, hyper = debug");

The parser rejects the string, and EnvFilter::new drops the bad directives silently. Write filter strings with no spaces: "info,hyper=debug".

A typo after the equals sign

// Wrong - "debg" is not a level
let filter = EnvFilter::new("my_app=debg");

With new, the bad directive vanishes silently and the filter enables almost nothing. With try_new, the same string returns an error that names the accepted levels. Use try_new while you are writing the string by hand.

A bare typo that becomes a target

// Wrong expectation - "debg" is a target, not a level
let filter = EnvFilter::new("debg");

This parses fine, enables the target debg at TRACE, and matches no real code, so nothing prints. If a filter string produces no output at all, check whether the first word is a level you misspelled.

Filtering your own crate off by accident

// Wrong - the specific rule wins and silences your own crate
let filter = EnvFilter::new("info,my_app=off");

The off rule is more specific than the info rule, so your own events are all disabled. Use off on dependencies, not on your own crate.

Forgetting the env-filter feature

// Wrong without features = ["env-filter"] - will not compile
use tracing_subscriber::EnvFilter;

The compiler reports that EnvFilter does not exist. The fix is the feature flag in Cargo.toml, exactly as shown at the top of this page.

Testing a Filter

Filters are pure string parsing, so they are the easiest part of tracing to test. This test file checks the parsing facts from this page: a bare level sets the maximum, a per-target directive raises it, a bad level after the equals sign is an error, and a bare unknown word parses as a target.

// tests/filter_tests.rs
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::EnvFilter;

#[test]
fn bare_level_parses_to_a_max_level() {
    let filter = EnvFilter::new("info");
    assert_eq!(filter.max_level_hint(), Some(LevelFilter::INFO));
}

#[test]
fn per_target_directive_parses() {
    let filter = EnvFilter::new("info,my_app=debug");
    assert_eq!(filter.max_level_hint(), Some(LevelFilter::DEBUG));
}

#[test]
fn bad_level_after_equals_is_an_error() {
    assert!(EnvFilter::try_new("my_app=debg").is_err());
}

#[test]
fn bare_unknown_word_parses_as_a_target() {
    assert!(EnvFilter::try_new("debg").is_ok());
}

#[test]
fn add_directive_extends_a_filter() {
    let filter = EnvFilter::new("info");
    let filter = filter.add_directive("my_app=debug".parse().unwrap());
    assert_eq!(filter.max_level_hint(), Some(LevelFilter::DEBUG));
}

Run the tests with cargo test. All five pass. The max_level_hint method returns the most detailed level any directive in the filter allows, wrapped in Some, or None when the filter enables nothing at all. These tests need the env-filter feature enabled, and they need no subscriber installed, because parsing a filter string touches no global state.

Final Complete Example

Here is a program that puts the page together: a filter with a default, a per-crate rule, a silenced dependency, and a span filter, all in one string, with events that show which rule let each line through.

// src/main.rs
use tracing_subscriber::EnvFilter;

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::new(
            "warn,filter_demo=debug,hyper=off,filter_demo[checkout{user_id=42}]=trace",
        ))
        .init();
    tracing::info!("info from your own crate, shown by the per-crate rule");
    tracing::debug!("debug from your own crate, shown by the per-crate rule");
    let span = tracing::info_span!("checkout", user_id = 42);
    let _guard = span.enter();
    tracing::trace!("trace inside the matching span, shown by the span rule");
}

The string has four directives. warn is the default for everything else. filter_demo=debug raises your own crate to DEBUG. hyper=off silences the HTTP crate. filter_demo[checkout{user_id=42}]=trace raises TRACE for events inside a matching checkout span. Each line in the output exists because exactly one of those rules let it through, and a line that matches no rule never appears.

Summary

An EnvFilter is a list of rules, and each rule is a target, a level, or a span test, joined by an equals sign and separated by commas. The filter picks the most specific matching rule for each event, and the bare level is only the fallback when nothing specific matches. The parsing has two faces: after the equals sign the parser is strict and names the levels it accepts, but a bare word is always read as a target, so a misspelled level silently becomes a rule that matches nothing. The practical rule that follows from all of this is to build filters with try_new while you are writing them, to write them with no spaces, and to test them with the small test file above before trusting them in a running server. The next question is where those strings live when they are not written in code, and that question is answered by the environment variable that carries them.