How to use tracing for request logging in Axum

Enable request logging in Axum by adding the tracing crate, initializing a subscriber, and instrumenting handlers.

Add the tracing and tracing-subscriber crates to your dependencies, then configure a subscriber in main and apply the tracing::instrument macro to your Axum handlers to log request details.

[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.3"
use axum::{routing::get, Router};
use tracing_subscriber;

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();
    let app = Router::new().route("/hello", get(hello));
    axum::serve(
        tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(),
        app.into_make_service(),
    )
    .await
    .unwrap();
}

#[tracing::instrument]
async fn hello() -> &'static str {
    "Hello, world!"
}