How to Use Spans for Request Tracing in Rust

Use the tracing crate and instrument macro to create spans for request tracing in Rust.

Use the tracing crate to create spans that automatically track request execution context in Rust. Add the dependency to your Cargo.toml and wrap your request logic in a #[instrument] macro to generate structured logs with parent-child relationships.

use tracing::{info, instrument};

#[instrument]
fn handle_request(request_id: &str) {
    info!(request_id, "Processing request");
    // Your logic here
}

Run your application with RUST_LOG=info cargo run to see the traced output in the console.