How to Add Logging and Tracing to Rust Web Applications

Add the `tracing` and `tracing-subscriber` crates to your `Cargo.toml`, initialize the subscriber in `main`, and use the `#[instrument]` attribute on functions to automatically log entry, exit, and arguments.

How to Add Logging and Tracing to Rust Web Applications

Add the tracing and tracing-subscriber crates to your Cargo.toml, initialize the subscriber in main, and use the #[instrument] attribute on functions to automatically log entry, exit, and arguments.

[dependencies]
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tokio = { version = "1", features = ["full"] }
use tracing::{info, instrument};
use tracing_subscriber;

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .init();

    info!("Server starting");
    handle_request("/api/data").await;
}

#[instrument]
async fn handle_request(path: &str) {
    info!("Processing request for path: {}", path);
    // Simulate work
    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}