Rust Recipes is a problem-oriented series of articles that assist developers while learning Rust. Every article solves simple, everyday development tasks using the Rust standard library or leveraging popular and proven crates.

Question: How to add structured logging to a Rust application?

println! gets you surprisingly far, but it falls short as soon as you need log levels, want to filter output without recompiling, or ship logs to a system that expects JSON. The tracing crate solves all of that. It separates emitting events (the tracing crate) from collecting and formatting them (a subscriber, here from tracing-subscriber ).

First, let’s add both crates using cargo add. The env-filter feature lets us control verbosity with the RUST_LOG environment variable, and json adds a JSON formatter:

BASH
# Add tracing as dependency
cargo add tracing
# Add tracing-subscriber with filtering and JSON support
cargo add tracing-subscriber --features env-filter,json

Emit Events With Fields

tracing provides one macro per level: trace!, debug!, info!, warn! and error!. Besides a message, every event can carry key-value fields. That’s the “structured” part: total ends up as its own field instead of being baked into a string:

RUST
use tracing::{debug, info, instrument, warn};
use tracing_subscriber::EnvFilter;

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

    info!("starting order processing");
    let total = process_order(42, &["keyboard", "mouse"]);
    info!(total, "order processed");
    process_order(43, &[]);
}

#[instrument]
fn process_order(order_id: u64, items: &[&str]) -> u32 {
    debug!(count = items.len(), "validating items");
    if items.is_empty() {
        warn!("order has no items");
        return 0;
    }
    items.len() as u32 * 25
}

tracing_subscriber::fmt() builds a subscriber that writes human-readable lines to stdout, and init() installs it globally. Call it once, as early as possible in main. Events emitted before that point are dropped.

EnvFilter reads the filter from RUST_LOG. If the variable isn’t set, we fall back to info, so debug! events stay hidden by default.

Add Context With Spans

The #[instrument] attribute wraps process_order in a span. A span represents a period of time, and every event emitted inside it automatically carries the span’s fields. Here, that’s the function arguments order_id and items. Running the app prints this:

BASH
cargo run
TEXT
2026-11-20T06:05:35.641886Z  INFO logging: starting order processing
2026-11-20T06:05:35.642201Z  INFO logging: order processed total=50
2026-11-20T06:05:35.642228Z  WARN process_order{order_id=43 items=[]}: logging: order has no items

The warning tells us which order had no items, even though the warn! call itself doesn’t mention the order ID. That’s the real value of spans: context flows down to every event without passing it around manually.

If a function takes arguments that are large or sensitive, exclude them with #[instrument(skip(password))], or record only what you need with #[instrument(skip_all, fields(user_id = user.id))].

Filter With RUST_LOG

Because we use EnvFilter, we can change verbosity at runtime without touching the code:

BASH
RUST_LOG=debug cargo run
TEXT
2026-11-20T06:05:35.777536Z  INFO logging: starting order processing
2026-11-20T06:05:35.777767Z DEBUG process_order{order_id=42 items=["keyboard", "mouse"]}: logging: validating items count=2
2026-11-20T06:05:35.777792Z  INFO logging: order processed total=50
2026-11-20T06:05:35.777806Z DEBUG process_order{order_id=43 items=[]}: logging: validating items count=0
2026-11-20T06:05:35.777819Z  WARN process_order{order_id=43 items=[]}: logging: order has no items

Filters can also target individual crates or modules. For example, RUST_LOG=info,my_app=debug keeps dependencies at info while showing debug events from your own crate (replace my_app with your crate name).

Switch to JSON Output

Log aggregators prefer one JSON object per line. Thanks to the json feature, that’s a one-line change in main:

RUST
tracing_subscriber::fmt()
    .json()
    .with_env_filter(
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
    )
    .init();

Every event now becomes a JSON object, with its fields and the surrounding span nested as data:

JSON
{"timestamp":"2026-11-20T06:05:42.346814Z","level":"WARN","fields":{"message":"order has no items"},"target":"logging","span":{"items":"[]","order_id":43,"name":"process_order"},"spans":[{"items":"[]","order_id":43,"name":"process_order"}]}

A common pattern is to pick the format at startup, for example human-readable output during local development and JSON in production, based on an environment variable or a command-line flag.

Recap

With tracing and tracing-subscriber, structured logging in Rust takes a few lines: emit events with key-value fields, wrap functions in spans with #[instrument] to get context for free, control verbosity with RUST_LOG, and switch to JSON output with .json() when logs leave your machine.