trace debug info warn error levels

Learn the five tracing levels TRACE DEBUG INFO WARN and ERROR, what each one is for, how filtering hides the lower ones, and how to pick the right level for every log line

Every log line carries a level, and the level is a statement about how much the line matters. There are five levels, and they form a single ladder from the most detailed to the most urgent: TRACE, DEBUG, INFO, WARN, and ERROR. A TRACE line records a tiny step inside a function. An ERROR line records a failure that needs a human. The level decides two things: whether the line is printed at all, and how loudly it should be treated by the people and tools that read the logs.

Where This Fits

The request span groups lines by request, and the JSON formatter prints the level as a searchable key. Levels decide which of those lines survive. A server running at INFO maximum prints its milestones and its failures, and hides its fine detail. The same server running at DEBUG maximum prints the detail too, for the afternoon someone is tracking a bug. Nothing in the code changes between those two runs. Only the level setting changes, and the setting reads the levels the code already assigned. Choosing levels well is what makes that setting useful. Choose them badly, and the filter either hides the failures or drowns the reader in noise.

Think of the levels as the triage tags in an emergency room. Every patient gets a tag, and the tag decides who is seen first. A green tag means routine. A red tag means now. The tags do not change the treatment, but they decide the order, and a patient tagged wrong is either ignored when they need help or rushed ahead of someone sicker. A log line tagged wrong does the same damage to the person reading the logs.

The Five Levels in One Table

The ladder has five rungs. Each rung has a name, a question it answers, and a typical reader.

LevelQuestion it answersWho reads it
TRACEWhat exactly happened, step by stepA developer tracing one flow
DEBUGWhy did this behave this wayA developer diagnosing a bug
INFOWhat is the server doingAn operator watching normal running
WARNWhat went odd but still workedAn operator watching for trouble ahead
ERRORWhat failed and needs a humanAn operator or an alerting tool, now

The order matters more than any single definition. TRACE is the most verbose, the most detail. ERROR is the least verbose, the most urgent. Setting a maximum level keeps that level and everything more urgent than it, and hides everything more detailed. A maximum of INFO keeps INFO, WARN, and ERROR. A maximum of WARN keeps WARN and ERROR. A maximum of ERROR keeps only ERROR.

The ordering is not just a convention. It is built into the Level type, and a program can compare levels directly. This was verified by running a program that printed the result of the comparison:

TRACE > DEBUG > INFO > WARN > ERROR is true

That line came from a real run, and it says the ordering in code matches the ordering in the table. The Level values also print as plain strings: Level::INFO formats as INFO, which is the same string the JSON formatter writes into the level key.

The Smallest Working Version

Five log calls, one handler, one server. Each call uses a different level, and the same request shows which lines survive at the default setting.

src/main.rs
use axum::{routing::get, Router};

async fn checkout() -> &'static str {
    tracing::trace!(step = "enter checkout", "entering checkout handler");
    tracing::debug!(cart_items = 3, "cart contents checked");
    tracing::info!(user_id = 42, "checkout started");
    tracing::warn!(attempts = 3, "payment retry, card declined twice before");
    tracing::error!(reason = "database connection refused", "checkout failed");
    "checkout attempted"
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();

    let app = Router::new().route("/checkout", get(checkout));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("server listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The subscriber reads the level from the RUST_LOG environment variable, and falls back to info when the variable is not set. The env-filter feature on tracing-subscriber is what makes the EnvFilter type available. Run the server with plain cargo run, so the fallback applies, and send a request:

curl http://127.0.0.1:3000/checkout

The server terminal shows three lines, verified by running this program. Timestamps and colour codes are omitted here for readability:

INFO t16: checkout started user_id=42
WARN t16: payment retry, card declined twice before attempts=3
ERROR t16: checkout failed reason="database connection refused"

The TRACE line and the DEBUG line are missing. They were written by the handler, and the subscriber dropped them before printing, because the maximum level is INFO and both lines are more detailed than INFO. The handler ran all five calls. The filter decided which three reached the terminal. The t16 in each line is the crate name of the test program that produced the output. In your project it reads your own crate name.

Three lines at the default level means filtering works:

With no RUST_LOG set, one request to this handler must print exactly three lines: INFO, WARN, and ERROR. If five lines appear, the level is set to TRACE somewhere. If no lines appear, no subscriber is installed or the level is set to off. If only the ERROR line appears, the level is set to ERROR.

TRACE - The Finest Detail

TRACE is the most detailed level, and it exists for one situation: following a single flow step by step when something is wrong and the cause is not visible at any higher level. A TRACE line records the small facts a developer needs while reading code with a running program beside it: entering a function, the value of a variable at one point, the branch a condition took, the exact bytes of a message before parsing.

src/main.rs
tracing::trace!(step = "enter checkout", "entering checkout handler");
tracing::trace!(item_id = 7, price = 1999, "price looked up for item");

The first line marks entry into the handler. The second records one lookup with its inputs. Neither line matters to an operator. Both matter to a developer who is tracing why the seventh item priced wrong, because they show the exact values the code saw, in the exact order it saw them.

TRACE lines are the most numerous by far. A single request can produce dozens of them, one per step, and a busy server can produce thousands per second. That volume is why TRACE is never the default in production. It is a tool switched on for one investigation and switched off again when the investigation ends. The per-crate filter below shows how to switch it on for one crate only, so the rest of the system stays quiet.

A beginner mistake is treating TRACE as a place for routine detail that feels too small for DEBUG. The test is the reader: if the line only helps someone reading the code line by line while the program runs, it is TRACE. If it helps someone understand why a decision was made, it is DEBUG.

DEBUG - Diagnosis Detail

DEBUG is the level for the facts that explain behaviour. A DEBUG line records a decision and its reason, a value the code computed, a cache hit or miss, a retry count, the size of a result. It answers the question a developer asks when a feature works but not as expected: what did the code actually do.

src/main.rs
tracing::debug!(cart_items = 3, "cart contents checked");
tracing::debug!(cache = "miss", key = "user:42", "user cache miss, loading from database");

The first line records a check the handler performed, with the count it found. The second records a cache miss, with the key that missed, and the consequence, which is a database load. Both lines are useful the week someone reports that checkouts are slow, because they show whether the slowness came from the cart or from the cache. Neither line is useful to an operator watching the server run normally, which is why DEBUG stays hidden at the INFO default.

DEBUG is the level for development. A server run on a developer machine usually runs at DEBUG maximum, because the developer is the reader and the detail is the point. The habit to build is writing DEBUG lines at the points where a future bug will hide: the branch taken, the value used, the fallback chosen. A bug that leaves no DEBUG trace takes longer to find than one that does.

INFO - Normal Milestones

INFO is the level for the normal story of the server. An INFO line records a milestone in work that went as expected: the server started, a checkout completed, a report was generated, a user logged in. It answers the question an operator asks when checking that the server is alive and working: what has it done lately.

src/main.rs
tracing::info!(user_id = 42, "checkout started");
tracing::info!(user_id = 42, order_id = "ord-1042", "checkout completed");

The two lines mark the start and the end of one checkout. Together they show that the work began and that it finished, and the order id on the second line lets the reader find the order in the database. An operator scanning INFO lines sees a steady rhythm of starts and completions, and a gap in the rhythm means the server stopped doing work.

INFO is the default maximum for a reason. It is the level where the volume stays readable and the content stays useful. A server that logs one INFO line per request produces a readable record of its life. A server that logs ten INFO lines per request produces a record nobody reads, and the milestones drown in their own detail. The rule for INFO is one or two lines per unit of work: one when it starts, one when it finishes, and nothing in between unless something went wrong.

WARN - Odd but Handled

WARN is the level for something odd that the program handled on its own. A WARN line records a situation that is not normal, did not fail, and might become a failure if it keeps happening: a retry that succeeded on the second try, a deprecated call that still works, a request that took much longer than usual, a disk that is filling up.

src/main.rs
tracing::warn!(attempts = 3, "payment retry, card declined twice before");
tracing::warn!(latency_ms = 2400, "checkout took longer than usual");

The first line records a payment that failed twice and succeeded on the third attempt. The work completed, so it is not an error, but two declined cards in one checkout is odd enough to notice. The second records a slow checkout. Nothing failed, but a checkout that usually takes a fraction of a second taking over two seconds is a sign worth keeping.

WARN lines are the early warning system of the logs. An operator who watches WARN lines sees trouble coming: retries climbing, latencies rising, a deprecated path still in use. A server with no WARN lines is either healthy or blind, and the difference shows in whether the ERROR lines arrive as a surprise. The mistake to avoid is using WARN for failures. A checkout that failed is an ERROR, not a WARN, because it needs action now, and a WARN line does not trigger the alert an ERROR line does.

ERROR - Failed and Needs a Human

ERROR is the level for work that failed and needs a human to look at it. An ERROR line records the failure and the reason, with enough context to act on: which user, which order, which error, and what the program was doing when it failed. It is the only level that should wake someone up, page someone, or open an incident.

src/main.rs
tracing::error!(reason = "database connection refused", "checkout failed");
tracing::error!(user_id = 42, order_id = "ord-1042", error = "timeout after 30s", "payment charge failed");

The first line records a checkout that failed because the database refused the connection. The second records a payment charge that timed out, with the user and the order it belonged to. Both lines name the failure and the reason, and both carry the identifiers a human needs to find the affected work. An ERROR line without the reason is a dead end: it says something failed and gives the reader nowhere to start.

ERROR lines should be rare. A server that logs an ERROR line every few seconds is either genuinely broken, in which case the errors are the story, or it is logging routine problems at ERROR level, in which case the level has lost its meaning. Every ERROR line should be actionable: something a human can fix, retry, or escalate. A line that nobody can act on should be a WARN line, or no line at all.

ERROR is for failures, not for emphasis:

Logging a routine event at ERROR level because it feels important trains everyone to ignore ERROR lines, including the alerting tool. When a real failure arrives, it looks like the last hundred routine errors. Keep ERROR for failures that need a human, and the level keeps its power.

The Concept Behind Levels

A level is a contract between the code that writes a line and the reader who sets the filter. The writer promises to tag each line honestly: routine work at INFO, diagnosis detail at DEBUG, failures at ERROR. The reader promises to set a maximum and trust it: INFO in production, DEBUG while diagnosing, TRACE for one deep investigation. The contract works because both sides use the same five names with the same meanings.

The filter is a ceiling on verbosity, not a selection of one level. Setting the maximum to INFO does not show only INFO lines. It shows INFO, WARN, and ERROR, everything at that urgency or above. Setting the maximum to WARN shows WARN and ERROR. Setting it to ERROR shows only ERROR. The ladder runs in one direction, and the setting picks how far down the ladder the reader is willing to go.

A mental model that helps is a volume knob with five stops. Turn it to TRACE and everything comes through, including the noise. Turn it to ERROR and only the failures come through, and the server sounds silent until something breaks. Production sits at INFO, the middle stop, where the milestones and the failures come through and the fine detail stays out.

How Filtering Hides the Lower Lines

The same handler, run under different level settings, prints different lines, and the differences show the filter at work. Each run below used the same program and the same request, with only RUST_LOG changed. Timestamps and colour codes are omitted for readability, and each run was verified live.

With no RUST_LOG set, the fallback is INFO, and three lines appear:

INFO t16: checkout started user_id=42
WARN t16: payment retry, card declined twice before attempts=3
ERROR t16: checkout failed reason="database connection refused"

With RUST_LOG=warn, the INFO line disappears and two lines remain:

WARN t16: payment retry, card declined twice before attempts=3
ERROR t16: checkout failed reason="database connection refused"

With RUST_LOG=debug, the DEBUG line appears and four lines show:

DEBUG t16: cart contents checked cart_items=3
INFO t16: checkout started user_id=42
WARN t16: payment retry, card declined twice before attempts=3
ERROR t16: checkout failed reason="database connection refused"

With RUST_LOG=trace, all five handler lines appear, and one more line appears that the handler never wrote:

TRACE axum::serve: connection 127.0.0.1:58030 accepted
TRACE t16: entering checkout handler step="enter checkout"
DEBUG t16: cart contents checked cart_items=3
INFO t16: checkout started user_id=42
WARN t16: payment retry, card declined twice before attempts=3
ERROR t16: checkout failed reason="database connection refused"

The extra TRACE line comes from Axum itself, which logs each accepted connection at TRACE level. At TRACE maximum, every library the server uses starts talking, and the volume grows fast. That is the TRACE flood, and it is why the next section keeps TRACE to one crate at a time.

With RUST_LOG=error, only one line survives:

ERROR t16: checkout failed reason="database connection refused"

Five settings, five different outputs, one program. The level setting is the whole difference, and the handler code never changed.

Controlling Levels Per Crate

A global level is a blunt tool. A developer debugging one crate wants its TRACE lines, but not the TRACE lines of every library the server uses. The filter accepts per-crate levels as a comma separated list, with the most specific rule winning.

RUST_LOG=my_app=trace,tower_http=warn,axum=off cargo run

This shows TRACE lines from your own crate, only WARN and ERROR from the tracing layer crate, and nothing at all from Axum. Replace my_app with your own crate name, with hyphens turned into underscores. The value off is a level that hides everything from that crate, and it exists on the filter type, which is called LevelFilter, rather than on the Level type itself.

This was verified by running the checkout server with RUST_LOG=t16=trace,tower_http=warn,axum=off. The output held all five handler lines, from TRACE to ERROR, and no line from Axum at all. The connection accepted TRACE line from the previous run was gone, because Axum was set to off, while the handler own TRACE line stayed, because its crate was set to trace.

The per-crate form is the answer to the TRACE flood. Turn your own crate up to TRACE, leave the libraries at WARN, and the investigation stays readable. Turn a noisy library down to ERROR while leaving your own crate at DEBUG, and the bug hunt keeps its detail without the library noise.

LevelFilter has OFF, Level does not:

The Level type holds the five levels only. The LevelFilter type holds the same five plus OFF, which hides everything. Code that sets a maximum level with .with_max_level accepts a LevelFilter, so LevelFilter::OFF is the value that silences a subscriber entirely. It is useful in tests that must produce no output, and nowhere else.

Setting the Level in Code

The environment variable is the usual control, but the level can also be fixed in code with .with_max_level. The two controls do the same job, and the environment one wins in practice because it changes without a rebuild. The code form fits a program that must never print below a level, or a test that needs a fixed level regardless of the environment.

src/main.rs
tracing_subscriber::fmt()
    .json()
    .with_max_level(tracing::Level::WARN)
    .init();

With this subscriber, only WARN and ERROR lines appear, whatever RUST_LOG says, because no environment filter is installed to read it. Do not call both .with_max_level and .with_env_filter on the same builder. The second call replaces the first, silently, and the reader of the code cannot tell which one won without knowing that rule. Pick one control per subscriber and use it consistently.

Where Plain Printing Still Fits

Tracing levels are the structured alternative to plain printing, not a replacement that makes printing wrong. A println! writes a line to standard output, and an eprintln! writes a line to standard error, and neither one carries a level, a timestamp, or a filter. That simplicity is a weakness in production and a strength in small places.

Plain printing still fits in three places. The first is the startup message, the line that tells the person who started the server where it is listening. The second is a tiny one-off program or script, where setting up a subscriber costs more than the program is worth. The third is a quick log inside a spawned task, where the task records its own failure with the job named and the error printed, a pattern that keeps the failure visible without any setup at all.

What plain printing cannot do is the job levels do: hide detail in production, surface failures to an alerting tool, and carry structured fields a search tool can filter on. A failure printed with eprintln! reaches the terminal, and a failure logged with tracing::error! reaches the terminal, the JSON log file, and the alerting tool, with its level attached. Use printing where the reader is a person watching a terminal, and use tracing levels where the reader is a system that must decide what matters.

Printing is not wrong, it is unfiltered:

A println! line is not a mistake. It is a line with no level, which means no filter can hide it and no alert can fire on it. That is fine for a startup message and a problem for a failure in production, where the line must be findable among thousands of others. The choice is about who reads the line, not about which macro is better.

Choosing a Level for a Real Handler

The five definitions are easy to state and hard to apply in the moment, so here is one handler with all five levels used the way they are meant to be used. The handler is a checkout, and each line sits at the point where its level fits.

src/main.rs
async fn checkout() -> &'static str {
    tracing::trace!(step = "enter checkout", "entering checkout handler");
    tracing::debug!(cart_items = 3, "cart contents checked");
    tracing::info!(user_id = 42, "checkout started");
    tracing::warn!(attempts = 3, "payment retry, card declined twice before");
    tracing::info!(user_id = 42, order_id = "ord-1042", "checkout completed");
    "Order confirmed"
}

The TRACE line marks entry, for the developer tracing the flow. The DEBUG line records the cart check, for the developer diagnosing a slow checkout. The first INFO line marks the start of the work, for the operator. The WARN line records the retries that succeeded, for the operator watching for trouble. The second INFO line marks the completion, with the order id, for the operator and for the record. Nothing here is an ERROR, because nothing failed.

The test for each line is a question about its reader. If the line helps only a developer reading the code while it runs, it is TRACE. If it helps a developer understand a decision, it is DEBUG. If it marks work starting or finishing, it is INFO. If it records something odd that still worked, it is WARN. If it records something that failed, it is ERROR. A line that fails every question is a line that should not exist.

How Levels Travel Through the System

A level set on a log call does not stay in the program. It travels with the line into every place the line goes, and each place uses it the same way. In the terminal, the level is a word at the start of the line, coloured by severity. In JSON output, the level is the string in the level key, and a search tool filters on it with an exact match, such as select(.level == "ERROR"). In an alerting tool, the level decides whether the line wakes someone up. The level is the one fact about a line that every reader agrees on, which is why it is the first key a search uses and the first word a person reads.

The flow from a log call to a filtered line has four stops:

tracing::error! call in the handler
        |
        v
event is created with level ERROR and its fields
        |
        v
subscriber checks the level against the maximum, keeps ERROR, drops TRACE and DEBUG
        |
        v
formatter prints the line with its level, to the terminal, a file, or a collector

The level check happens before formatting, so a dropped event costs almost nothing and leaves no trace. The formatter only runs for events that survive, and the level it prints is the level the code assigned. No step re-decides the level. The code decides, the filter enforces, and the formatter reports.

Testing That Filtering Hides the Lower Lines

A test can check filtering without a running server, by building a subscriber that writes JSON to a file with a fixed maximum level, logging lines at two levels, and reading the file back. The test below sets the maximum to ERROR, logs one INFO line and one ERROR line, and asserts that exactly one line survived and that it is the ERROR line.

tests/level_filter_test.rs
use std::fs::File;

#[test]
fn error_max_level_hides_info_lines() {
    let path = "target/test-level-logs.jsonl";
    let file = File::create(path).unwrap();
    let subscriber = tracing_subscriber::fmt()
        .json()
        .with_writer(file)
        .with_max_level(tracing::Level::ERROR)
        .finish();
    tracing::subscriber::with_default(subscriber, || {
        tracing::info!("this info line must be filtered out");
        tracing::error!(reason = "db down", "checkout failed");
    });
    let text = std::fs::read_to_string(path).unwrap();
    assert_eq!(text.lines().count(), 1);
    let value: serde_json::Value =
        serde_json::from_str(text.lines().next().unwrap()).unwrap();
    assert_eq!(value["level"], "ERROR");
    assert_eq!(value["fields"]["reason"], "db down");
    assert!(value["timestamp"].is_string());
}

The subscriber is built with .finish() instead of .init(), because a test must not install a global subscriber that other tests could clash with. The with_default call runs the closure with this subscriber active only inside the closure. The file is read back after the closure returns, so the writes have finished. The assertions check three things: exactly one line survived, it parses as JSON, and the level and the extra field hold the values the log call recorded.

The test needs serde_json as a dependency, which is listed in the Cargo.toml of the final complete example below. Run it with cargo test, and the output ends with test result: ok. This exact test was run and passed. A second test worth adding asserts the level ordering directly, because the ordering is the rule the filter depends on:

src/main.rs
#[test]
fn level_ordering_is_trace_to_error() {
    assert!(tracing::Level::TRACE > tracing::Level::DEBUG);
    assert!(tracing::Level::DEBUG > tracing::Level::INFO);
    assert!(tracing::Level::INFO > tracing::Level::WARN);
    assert!(tracing::Level::WARN > tracing::Level::ERROR);
}

Common Beginner Mistakes

Logging routine events at ERROR

// Wrong - a routine event at ERROR trains everyone to ignore ERROR lines
tracing::error!(user_id = 42, "user logged in");

A login is a normal milestone, and it belongs at INFO. Logged at ERROR, it joins the failure stream, and the alerting tool fires on a routine event. After enough false alarms, the alerts get ignored, and a real failure hides among them. The rule is blunt: if nobody needs to act on it, it is not an ERROR.

Logging failures at INFO

// Wrong - a failure at INFO is invisible to every ERROR filter and alert
tracing::info!("checkout failed: database connection refused");

A failure logged at INFO never reaches an alert, never appears in an ERROR search, and never wakes anyone up. The line exists in the logs, and nobody finds it until a user complains. A failure is an ERROR by definition, because a failure is what the level means.

Running TRACE in production

// Wrong as a default - TRACE maximum in production floods the logs
tracing_subscriber::fmt()
    .with_max_level(tracing::Level::TRACE)
    .init();

A TRACE maximum in production prints every step of every request, plus the TRACE lines of every library, and the volume buries the failures. TRACE is an investigation setting, switched on for one crate and one problem, then switched off. The per-crate filter is the way to do that without flooding the rest of the system.

Setting RUST_LOG to trace to debug one crate

# Wrong - this turns every crate to TRACE, not just yours
RUST_LOG=trace cargo run

A global trace turns on TRACE for every crate in the program, including the web framework and the HTTP library, and the output becomes unreadable. The per-crate form, RUST_LOG=my_app=trace, turns on TRACE for your crate only and leaves the libraries at their default. The global form is for the rare case where the bug is in a library itself.

Forgetting the subscriber entirely

// Wrong - no subscriber means no output at all, at any level
async fn checkout() -> &'static str {
    tracing::error!("checkout failed");
    "checkout attempted"
}

Without a subscriber, every tracing call silently does nothing. The compiler does not warn about it, and the server runs fine, except that no logs appear. The fix is one call at the start of main, before the router is built. If no log lines appear at all, check the subscriber before checking the levels.

Using log macros instead of tracing macros

// Wrong here - the log crate does not know about spans or levels in tracing
log::info!("checkout started");

The log crate provides macros with the same names, log::info! and log::error!, but they are a different system. They do not know about tracing spans, so a line written with log::info! inside a request span carries no request context. Use the tracing macros when the program uses tracing, and keep the log macros for code that genuinely uses the log crate.

Final Complete Example

This example pulls the page together: a checkout handler that uses all five levels, a subscriber that reads the level from the environment with an INFO fallback, JSON output so the level is a searchable key, and a health route that logs a DEBUG line.

src/main.rs
use axum::{routing::get, Router};

async fn checkout() -> &'static str {
    tracing::trace!(step = "enter checkout", "entering checkout handler");
    tracing::debug!(cart_items = 3, "cart contents checked");
    tracing::info!(user_id = 42, "checkout started");
    tracing::warn!(attempts = 3, "payment retry, card declined twice before");
    tracing::error!(reason = "database connection refused", "checkout failed");
    "checkout attempted"
}

async fn health() -> &'static str {
    tracing::debug!("health check answered");
    "OK"
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .json()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();

    let app = Router::new()
        .route("/checkout", get(checkout))
        .route("/health", get(health));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("server listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
Cargo.toml
[package]
name = "level-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
serde_json = "1"

Run the server four ways and watch the output change while the code stays the same:

cargo run
RUST_LOG=warn cargo run
RUST_LOG=debug cargo run
RUST_LOG=level_demo=trace cargo run

The first run prints the INFO, WARN, and ERROR lines. The second prints only WARN and ERROR. The third adds the DEBUG line. The fourth adds the TRACE line from the handler but not the TRACE lines from Axum, because the per-crate filter turns on TRACE for this crate only. The crate name in the filter is the package name with hyphens turned into underscores, so level-demo becomes level_demo.

Summary

The decision this page teaches is not which level to use, but how to think about the five as a system. The levels are a ladder, and the filter is a ceiling, and the two together decide what any reader sees. The single most important insight is that the level is a promise about urgency, and the whole system trusts it: the filter trusts it to hide detail, the search tool trusts it to find failures, and the alerting tool trusts it to wake someone up. A level assigned carelessly breaks all three at once.

The framework for choosing is one question per line: who reads this, and what must they do about it. A developer tracing a flow reads TRACE. A developer diagnosing a bug reads DEBUG. An operator watching normal running reads INFO. An operator watching for trouble reads WARN. A human who must act now reads ERROR. When a line has no honest answer to that question, it has no level, and a line with no level is a line that should not be written. Get the tags right, and the same program serves the developer at TRACE, the operator at INFO, and the alerting tool at ERROR, with nothing in the code changing between them.