How to enable logging/tracing with Axum?

13.9k views Asked by At

I'm learning Axum and I will like to add logging to the service I have put together but unfortunately I cannot get it to work.

I have added tower-http to use the TraceLayer and added it to my app:

# Cargo.toml
[dependencies]
axum = "0.6.1"
tower-http = { version = "0.3.5", features = ["trace"] }
use tower_http::trace::TraceLayer;

let app = Router::new()
    .route("/:name/path", axum::routing::get(handler))
    .layer(TraceLayer::new_for_http())

But when I start the application and make requests to the endpoint, nothing gets logged. Is there any configuration step I could have missed?

1

There are 1 answers

2
kmdreko On BEST ANSWER

You need to set up a "subscriber" to output the tracing events created by the TraceLayer. You can get up and running quickly with the tracing-subscriber crate :

# Cargo.toml
[dependencies]
tracing = "0.1.37"
tracing-subscriber = "0.3.16"
tracing_subscriber::fmt()
    .with_max_level(tracing::Level::DEBUG)
    .init();

By default, TraceLayer will log with a DEBUG level so the .with_max_level is important for viewing those logs. You can change the behavior of TraceLayer by using the customizable on_* methods.

See also: