HTTP TraceLayer
Learn how TraceLayer adds request tracing to an Axum server, what it logs for each request, and how to set it up
TraceLayer is a piece of middleware that watches every HTTP request your Axum server handles and writes a short log record about it. Its one job is to give every request a traceable identity in your logs, so that later, when something goes wrong, you can find the exact request that caused it and see how long it took and what status it returned. You add it to your router in one line, and from then on each request produces a small set of log lines without any logging code inside your handlers.
Where This Fits
Log lines on their own tell you that something happened, but not which request it happened for. A tracing setup gives you events with levels and a subscriber that prints them, and TraceLayer builds on that by opening one span per request and attaching the method, the path, and the version to everything logged while that request is handled. Think of it as a name tag handed to each request at the door. Every log line produced while the request is inside wears that name tag, so you can sort the lines back into requests afterwards.
The Smallest Working Version
The setup has four steps. Add the dependencies with the trace feature, initialise a subscriber that shows DEBUG output, add the layer to the router, and run the server to check the output. Each step depends on the one before it.
[package]
name = "trace_demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
The trace feature is what makes TraceLayer exist at all. The tower-http crate ships its middleware behind feature flags, and without trace the import in the code below fails to compile. The tracing crate provides the macros used inside handlers, and tracing-subscriber provides the subscriber that prints events to the terminal. The env-filter feature enables filtering by the RUST_LOG environment variable, which is the usual way to control log levels without changing code.
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let app = Router::new()
.route("/", get(hello))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("server listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
tracing::info!("hello handler was reached");
"Hello, world!"
}
The subscriber line must come first in main, before the router is built. The .with_max_level(tracing::Level::DEBUG) part is doing real work here, not decoration. TraceLayer and its span are DEBUG level, and a plain fmt() subscriber only shows INFO and above. With a plain subscriber the server still runs, but you see none of the request context and none of the layer own lines. Run the server with cargo run, then send a request with curl http://127.0.0.1:3000. The terminal shows lines like these, verified by running the program. Timestamps and colour codes are left out here for readability.
DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_request: started processing request
INFO request{method=GET uri=/ version=HTTP/1.1}: hello handler was reached
DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=0 ms
Four lines appear for one request, and each one comes from a different moment in the request life. The rest of this page explains each moment in turn.
Four lines means it works:
If your terminal shows log lines with a request{method=... uri=...} prefix, TraceLayer is working. The started and finished lines confirm the layer own events are visible, and the prefix on your handler line confirms the span context is attached. If you see your handler lines but no prefix and no started or finished lines, the subscriber maximum level is the problem, and the plain subscriber trap below explains why.
Reading the Four Lines
The four lines look similar, but each one is produced by a different callback at a different point, and knowing which is which makes the logs readable instead of mysterious.
The started line
DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_request: started processing request
This line is emitted by the on_request callback the moment the request reaches the layer, before your handler runs. It carries no fields of its own. Everything useful on the line is in the span prefix: the method, the URI, and the HTTP version. The message itself is always the same text, started processing request. Its target, tower_http::trace::on_request, tells you which callback produced it. If you see this line, the request arrived and the span is open.
The handler line
INFO request{method=GET uri=/ version=HTTP/1.1}: hello handler was reached
This line is your own code, the tracing::info! call inside the handler. Nothing about the call itself mentions the method or the path. The span prefix appears because the handler runs while the request span is active, and the subscriber prints the active span in front of every event. This is the whole point of the layer. You write ordinary log calls, and the request context is attached for free.
The finished line
DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
This line is emitted by the on_response callback when your handler has produced a response. It carries two fields that the started line does not have. The latency field says how long the request took, measured from when the layer received it until the response was ready. The status field is the HTTP status code of the response, here 200. The latency reads 0 ms for a fast handler because the default unit is milliseconds and the value is a whole number of milliseconds, so anything under one millisecond shows as zero. That does not mean the request took no time. It means the request took less than a millisecond, and the default unit is too coarse to show it.
The end of stream line
DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=0 ms
This line is emitted by the on_eos callback when the response body has finished streaming to the client. It carries stream_duration, which measures the time from when the response was sent until the body finished, not the time the handler took. For a short plain-text body the stream finishes almost at once, so the value is 0 ms. The distinction matters for streamed responses, where the handler can finish quickly while the body keeps flowing for much longer. There is one more thing to know about this line. It is driven by the body being read to its end. In a live run, responses with an empty body, such as a handler that returns only a status code with no body text, produced no end of stream line at all even after waiting several seconds. The body was never read through the layer, so the end of the stream was never observed. A response with a real body always produced the line.
The Six Callbacks Behind the Lines
TraceLayer is not one fixed behaviour. It is six hooks, each firing at one point in the request life, and each one can be left at its default or replaced with your own code. The table below is a map of the six hooks. You do not need to memorise it now. Return to it when an example replaces one of these hooks and you want to know where that hook sits.
| Callback | When it fires | What it receives |
|---|---|---|
make_span_with | When the request arrives, before anything else | The request, and it returns the span |
on_request | When the request arrives, just before the handler runs | The request and the span |
on_response | When the handler has produced a response | The response, the latency, and the span |
on_body_chunk | Each time a piece of the response body is sent | The chunk, the time since the last chunk, and the span |
on_eos | When the response body stream ends | The trailers, the stream duration, and the span |
on_failure | When the response is classified as a failure | The failure classification, the latency, and the span |
The span is created first, by make_span_with, and every later callback receives a reference to that same span. That reference is what lets a later callback add information to the span that was not known when the span was created, such as the status code, which only exists once the response exists. The default span maker is DefaultMakeSpan, and the defaults for the other five are DefaultOnRequest, DefaultOnResponse, DefaultOnBodyChunk, DefaultOnEos, and DefaultOnFailure. The default for on_body_chunk does nothing at all, so a normal response produces no per-chunk lines unless you add a callback yourself.
A mental model that holds for all six is a relay race. The span is the baton. make_span_with creates the baton and writes the request details on it. Each callback takes the baton, does its small job, and passes it on. Nothing is passed through your handler code, and your handler never sees the baton unless it asks for it.
The Plain Subscriber Trap
The most common surprise with TraceLayer is running the program above with a plain subscriber, meaning tracing_subscriber::fmt().init() with no with_max_level call, and seeing output that looks broken. It is not broken. It is filtered. This was verified by running the same server twice, once with each subscriber. With a plain subscriber, whose maximum level is INFO, a single request produces exactly this one line.
INFO hello handler was reached
The handler own info line appears, but with no request context in front of it and no started or finished lines anywhere. The reason is the level system. The TraceLayer span is DEBUG level, so at an INFO maximum the span is disabled entirely, and an event with no active span prints with no context. The started, finished, and end of stream events are DEBUG level too, so they are filtered out as well. Nothing is wrong with the layer. The subscriber is simply not letting DEBUG output through.
There are two fixes, and they solve different problems. The first fix is to lower the subscriber maximum to DEBUG, with .with_max_level(tracing::Level::DEBUG), which is what the setup section does. That shows everything, the span context and the layer own events. The second fix is to raise the span level to INFO while leaving the subscriber at INFO, using DefaultMakeSpan, which is shown in the span customisation example below. That shows the span context on your handler lines, but the layer own DEBUG events stay hidden. Pick the first fix while you are developing, because seeing the started and finished lines helps you learn what the layer does. Pick the second fix when you want request context in production logs without the extra DEBUG noise.
A missing subscriber silently hides all logs:
If you forget to call tracing_subscriber::fmt().init(), none of your tracing::info! or tracing::error! calls produce any output. The compiler will not warn you, and your code will run perfectly fine except that you see no logs. This is one of the most common reasons beginners think TraceLayer is broken when it is actually working but its output is being discarded because no subscriber exists.
new_for_http and new_for_grpc
TraceLayer::new_for_http() is the constructor for an HTTP server, and it is the one to use in Axum. The name exists because tower-http also offers new_for_grpc(), which classifies responses using gRPC status codes instead of HTTP status codes. The two constructors differ in how they decide whether a response counts as a failure, and in how they read the status. For plain HTTP traffic, new_for_http classifies any 5xx status as a failure and reads the status from the HTTP status line.
Using the gRPC constructor on an HTTP server compiles and runs, which was verified by building a second small program with TraceLayer::new_for_grpc() on an Axum router. A plain HTTP request to it still logged finished processing request latency=0 ms status=200, because a non-gRPC response falls back to its HTTP status. That does not make it a good choice for an HTTP server. The failure classification would be wrong for ordinary HTTP traffic, so use new_for_http unless the service actually speaks gRPC.
There is also a third constructor, TraceLayer::new(...), which takes a classifier you build yourself. It exists for cases where neither the HTTP nor the gRPC rule fits, such as treating 404 responses as failures. For now, know that new_for_http is the default-shaped constructor, new_for_grpc is its gRPC twin, and new is the escape hatch.
What Counts as a Failure
new_for_http classifies a response as a failure when its status code is in the 5xx range, meaning a server error. When that happens, two things occur. The on_response callback still fires, exactly as it does for a success, and then the on_failure callback fires as well. The two callbacks are additive, not alternatives. The default on_failure logs at ERROR level, which is why a failed request stands out in the logs even when the subscriber is set to INFO.
Here is a small server with three routes, so the difference is visible side by side.
use axum::{http::StatusCode, routing::get, Router};
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let app = Router::new()
.route("/", get(hello))
.route("/not-found", get(not_found))
.route("/error", get(error_handler))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
tracing::info!("hello handler was reached");
"Hello, world!"
}
async fn not_found() -> StatusCode {
StatusCode::NOT_FOUND
}
async fn error_handler() -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
Request / and you see the familiar four lines with status=200. Request /not-found and the finished line reads status=404, with no failure line, because a 404 is a client error, not a server error, and the default classifier does not treat it as a failure. Request /error and the output gains a third line after the finished line, verified by running the program.
DEBUG request{method=GET uri=/error version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=500
ERROR request{method=GET uri=/error version=HTTP/1.1}: tower_http::trace::on_failure: response failed classification=Status code: 500 Internal Server Error latency=0 ms
The failure line has its own fields. The classification field names the failure in words, Status code: 500 Internal Server Error, and the latency field is the same request latency the finished line reported. The level is ERROR, so this line is visible even with a plain INFO subscriber, while the finished line above it stays hidden at DEBUG. That split is deliberate. A 500 is worth waking someone up for, and the layer makes sure it is seen.
onresponse always fires, onfailure only sometimes:
A 500 response produces both a finished line and a failure line, because on_response fires for every response while on_failure fires only when the response is classified as a failure. If you ever see a failure line without a finished line, the finished line was filtered by level, not skipped. Check the subscriber maximum before assuming the layer misbehaved.
Raising the Span Level
The second fix for the plain subscriber trap uses DefaultMakeSpan, the built-in span maker that TraceLayer uses by default. You can configure it instead of writing your own closure. The level method sets the level of the span.
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
use tracing::Level;
let trace_layer = TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO));
Drop this layer into the basic example in place of the plain TraceLayer::new_for_http() line, and change the subscriber to a plain fmt().init(). With this layer and a plain INFO subscriber, a request produces the handler line with its context attached, verified by running the program.
INFO request{method=GET uri=/ version=HTTP/1.1}: hello handler was reached
The span is INFO level now, so the subscriber no longer filters it out, and the handler event gains its context. The layer own started and finished events are still DEBUG level, so they stay hidden. That is the trade being made. You get the context without the extra lines. This is the right choice for production logs, where the started and finished line for every request would double the log volume, and the wrong choice while you are learning, when those lines show you what the layer does.
The same pattern works in the other direction. Raising only the on_response level to INFO, with DefaultOnResponse::new().level(Level::INFO), makes the finished line visible at INFO, but the line prints without any span context in front of it, because the span itself is still DEBUG and disabled. The finished line and the span context are controlled separately, and changing one does not change the other. That separation is easy to miss, and it is the reason the span level and the event level are set in different places.
Turning Parts Off
Every callback can be disabled by passing () in its place. Setting a callback to () means that step does nothing at all. This is useful when one of the default lines is noise for your application. The example below silences only the started line.
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let app = Router::new()
.route("/", get(hello))
.layer(TraceLayer::new_for_http().on_request(()));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
tracing::info!("hello handler was reached");
"Hello, world!"
}
A request now produces three lines instead of four, verified by running the program. The started line is gone, and everything else is unchanged.
INFO request{method=GET uri=/ version=HTTP/1.1}: hello handler was reached
DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=0 ms
Disabling a callback is not the same as removing the layer. The span is still created, the handler line still carries its context, and the finished line still fires. Only the one silenced step goes quiet. A configuration that only reports failures, with on_request(()), on_response(()), on_body_chunk(()), and on_eos(()) while keeping a custom on_failure, is a real pattern for a quiet production service that only speaks up when something breaks.
Composing the Layer with ServiceBuilder
In a larger application the router often carries several layers, and tower::ServiceBuilder keeps that list readable. TraceLayer composes like any other Tower layer. The example below is the layer used in the test suite for this page, and it passed as a test. It sets the span level, the request and response levels, the latency units, and the failure level in one chain.
use std::time::Duration;
use tower::ServiceBuilder;
use tower_http::{
trace::{DefaultMakeSpan, DefaultOnEos, DefaultOnFailure, DefaultOnRequest, DefaultOnResponse, TraceLayer},
LatencyUnit,
};
use tracing::Level;
let trace_layer = ServiceBuilder::new().layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
.on_request(DefaultOnRequest::new().level(Level::INFO))
.on_response(
DefaultOnResponse::new()
.level(Level::INFO)
.latency_unit(LatencyUnit::Micros),
)
.on_eos(DefaultOnEos::new().latency_unit(LatencyUnit::Micros))
.on_failure(DefaultOnFailure::new().level(Level::WARN))
.on_body_chunk(
|chunk: &bytes::Bytes, _latency: Duration, _span: &tracing::Span| {
tracing::debug!("sent a body chunk of {} bytes", chunk.len());
},
),
);
Each builder call returns a new layer with one setting changed, and the calls chain in any order. The on_body_chunk closure at the end replaces the default, which does nothing, with a DEBUG line per chunk. The bytes crate is already a dependency of Axum, so the bytes::Bytes type in the closure needs no extra entry in Cargo.toml for a program that already depends on Axum. The latency unit settings here are worth a second look. The response unit and the end of stream unit are set separately, on DefaultOnResponse and on DefaultOnEos. Changing one leaves the other at its default of milliseconds.
Layers apply to routes added before them:
The .layer() call wraps the routes that were registered before it. If you call .layer(TraceLayer::new_for_http()) before adding any routes, the layer wraps nothing and never fires. Always add routes first, then apply layers. The same rule applies inside a ServiceBuilder chain.
How a Request Flows Through the Layer
The full path of one request through TraceLayer looks like this, in order.
Client sends HTTP request
|
v
TraceLayer receives the request and make_span_with opens the request span
|
v
on_request fires: started processing request
|
v
Handler runs inside the span, handler log lines carry the span context
|
v
Handler returns a response, on_response fires: finished processing request
|
v
Response is classified: 5xx also fires on_failure at ERROR level
|
v
Response body streams to the client, on_body_chunk fires per chunk
|
v
Body stream ends, on_eos fires: end of stream
Two things in this flow catch beginners out. The first is that on_response fires when the response is produced, not when the client has received it. The body may still be streaming after the finished line appears, and the end of stream line is the one that marks the body as done. The second is that the span stays open for the whole flow, from the moment the request arrives until the body stream ends. That is why a log line emitted anywhere in the handler, or in any helper the handler calls, carries the same request context.
Testing It
Testing TraceLayer means testing that the router still answers correctly with the layer applied. Log text itself is not asserted, because log lines depend on timing and on the subscriber, and asserting on them makes tests brittle. The test below sends mock requests directly through the router, with no network connection, using tower::ServiceExt::oneshot. It needs tower as a dev dependency with the util feature.
use axum::{
body::Body,
http::{Request, StatusCode},
routing::get,
Router,
};
use tower::ServiceExt;
use tower_http::trace::TraceLayer;
fn app() -> Router {
Router::new()
.route("/", get(|| async { "Hello, world!" }))
.route("/error", get(|| async { StatusCode::INTERNAL_SERVER_ERROR }))
.layer(TraceLayer::new_for_http())
}
#[tokio::test]
async fn home_returns_ok() {
let response = app()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn error_route_returns_500() {
let response = app()
.oneshot(
Request::builder()
.uri("/error")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run the tests with cargo test. Both tests passed in the scratch project used to verify this page. The tests prove the layer does not change what the routes return. The log output itself is checked by eye, by running the server and curling it, which is how every output block on this page was produced.
Common Beginner Mistakes
Forgetting the trace feature
// Wrong - will not compile
use tower_http::trace::TraceLayer;
With tower-http = "0.7" and no features in Cargo.toml, this import fails to compile, because the trace module is not built without the feature. The error message names the missing module, which is the clue to look at the feature list rather than the import path.
Using log macros instead of tracing macros
The log crate provides macros named log::info! and log::error!. These look similar to tracing::info! and tracing::error!, but they behave differently. The log crate does not know about spans, so if you use log::info! inside a TraceLayer span, the output will not include the request context. You will see the message but no request{method=... uri=...} prefix. Stick to tracing macros when using TraceLayer.
Initialising the subscriber after building the router
The subscriber must be installed before any tracing macro runs, and the safest place is the first line of main. Installing it after the router is built usually still works for request logging, because no requests are handled before axum::serve starts, but any log call made during startup, such as a message printed while building state, would be silently discarded. Put the subscriber first and never think about it again.
Expecting the finished line to wait for the client
The latency on the finished line stops when the response is produced, not when the client finishes reading the body. A handler that returns a large streamed body shows a small latency and a much larger stream_duration. That is correct behaviour, not a bug. The two numbers measure two different intervals, and a streamed body can show a small latency next to a much larger stream duration.
Treating a 404 as a failure
A 404 is a client error, and the default classifier does not treat it as a failure, so no on_failure line appears for it. Beginners often expect the failure line for any error status. The classifier rule is 5xx only. Changing that rule is a deliberate choice that needs a custom classifier, used only when treating 404 responses as failures fits the application.
TraceLayer logs on its own, if DEBUG is enabled:
TraceLayer creates a span and emits its own DEBUG events, started processing request, finished processing request, and end of stream. If your handlers contain no tracing calls at all, you will still see those lines, provided the subscriber maximum level is DEBUG. What produces zero output is the combination most beginners actually run, a plain tracing_subscriber::fmt().init(), whose default maximum is INFO, silently filtering out every TraceLayer event. If you see nothing, check the subscriber maximum level before concluding TraceLayer is broken.
Final Complete Example
Here is everything from this page put together. One server, three routes, the default layer, a DEBUG subscriber, and a slow route that makes the latency field visible.
use axum::{http::StatusCode, routing::get, Router};
use std::time::Duration;
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let app = Router::new()
.route("/", get(hello))
.route("/slow", get(slow))
.route("/error", get(error_handler))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("server listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
tracing::info!("hello handler was reached");
"Hello, world!"
}
async fn slow() -> &'static str {
tokio::time::sleep(Duration::from_millis(150)).await;
"Slow response"
}
async fn error_handler() -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
[package]
name = "trace_demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
Run it with cargo run, then request the routes one at a time.
curl http://127.0.0.1:3000/
curl http://127.0.0.1:3000/slow
curl http://127.0.0.1:3000/error
The slow route produces a finished line with a latency near 150 milliseconds, verified by running the program: finished processing request latency=151 ms status=200. The error route produces the finished line with status=500 followed by the ERROR failure line. The fast route shows latency=0 ms, which is the millisecond truncation described above, not a zero-time request.
Summary
The decision to carry forward is about levels, not about code. While you are developing, run a DEBUG subscriber and the default TraceLayer, so you see the span context, the started and finished lines, and the failure lines. When the application goes to production, make a choice per line. If you want the context and nothing else, raise the span level to INFO with DefaultMakeSpan and keep the subscriber at INFO. If you want the full picture, keep DEBUG for your own crate and set tower_http to WARN, so the layer own lines stay quiet while your handler lines keep their context. And if the logs go to a machine that reads them, switch the format to JSON, because the span fields become searchable fields instead of text to parse by eye. The layer itself stays the same in every case. Only the level and the format change, and those two settings decide what you actually see.
The single most important insight is that TraceLayer does not add logging to your handlers. It adds identity to the logs you already write. The span is the identity, the callbacks are the moments when the layer speaks for itself, and everything else on this page, levels, classifiers, units, and custom spans, is a way of shaping what that identity looks like when it is printed. What remains after this page is practice: run the server, read the four lines for each request, and change one setting at a time until the output shows exactly what you need and nothing you do not.