Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Logging - Tracing

axum uses the tracing and tracing-subscriber crates for logging so we need to include both.

[package]
name = "axum-logging"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
axum = "0.8.8"
serde = { version = "1.0.228", features = ["derive"] }
tokio = { version = "1.50.0", features = ["full"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }

[dev-dependencies]
headers = "0.4.1"
http-body-util = "0.1.3"
tower = { version = "0.5.3", features = ["util"] }
use axum::{response::Html, routing::get, Router};
use tokio::net::TcpListener;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

#[tokio::main]
async fn main() {
    tracing_subscriber::registry()
        .with(tracing_subscriber::fmt::layer())
        .init();

    let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
    tracing::debug!("listening on {}", listener.local_addr().unwrap());
    tracing::info!("listening on {}", listener.local_addr().unwrap());
    tracing::warn!("listening on {}", listener.local_addr().unwrap());
    tracing::error!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, create_router()).await.unwrap();
}

fn create_router() -> Router {
    Router::new().route("/", get(handler))
}

async fn handler() -> Html<&'static str> {
    tracing::debug!("in handler");
    tracing::info!("in handler");
    Html("<h1>Hello, World!</h1>")
}

When we start the application with cargo run we’ll see line like this on the terminal:

2026-03-29T15:49:37.789551Z DEBUG axum_logging: listening on 127.0.0.1:3000
2026-03-29T15:49:37.789601Z  INFO axum_logging: listening on 127.0.0.1:3000
2026-03-29T15:49:37.789613Z  WARN axum_logging: listening on 127.0.0.1:3000
2026-03-29T15:49:37.789623Z ERROR axum_logging: listening on 127.0.0.1:3000

When we access the main page with a browser we’ll see two more lines:

2026-03-29T15:49:39.380861Z TRACE axum::serve: connection 127.0.0.1:44280 accepted
2026-03-29T15:49:39.381339Z DEBUG axum_logging: in handler
2026-03-29T15:49:39.381372Z  INFO axum_logging: in handler