Rust

tracing — Structured Logging Setup

admin by @admin ADMIN
7m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`tracing` is the structured-logging story for async Rust — better than `log` for anything tokio-based. Drop in this initializer and use `info!`, `warn!`, `error!` macros throughout.
Rust
Raw
// Cargo.toml:
// tracing            = "0.1"
// tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }

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

fn init_logging() {
    fmt()
        .with_env_filter(EnvFilter::try_from_default_env()
            .unwrap_or_else(|_| EnvFilter::new("info,myapp=debug")))
        .with_target(false)
        .compact()
        .init();
}

#[instrument(skip(password))]    // arg `password` redacted from logs
fn login(user: &str, password: &str) -> bool {
    debug!("verifying credentials");
    if password.is_empty() {
        warn!("empty password");
        return false;
    }
    info!(user, "user signed in");
    true
}

fn main() {
    init_logging();
    info!("application starting");
    login("alice", "hunter2");
    error!(retry_count = 3, "could not connect to database");
    // Run with: RUST_LOG=debug cargo run
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.