Tracing HTTP Requests with TraceLayer
Learn how to use the tower-http TraceLayer middleware to automatically attach request context to logs in Axum applications, customize span fields, and handle request logging with practical examples.
When a web server receives hundreds of requests per minute, a plain log message like "database query failed" becomes nearly useless. You can see that something went wrong, but you cannot tell which endpoint was being called, which HTTP method was used, or which specific request triggered the failure. TraceLayer solves that problem by attaching request context to every log message your handlers produce, automatically. This page teaches you how to set it up, what it actually prints, how to customise the context it captures, and how to avoid the level setting that makes beginners think it is broken.
The Problem TraceLayer Solves
A typical Axum handler without tracing looks like this.
async fn get_user() -> &'static str {
println!("fetching user from database");
"User data"
}
If fifty clients call get_user at the same time and one of them hits an error, the printed output shows the message but gives you no way to know which of the fifty requests it belonged to. You cannot see the HTTP method, the path, or anything else that would help you reproduce the issue.
You could pass the request data into every log call by hand.
use axum::http::{Method, Uri};
async fn get_user(method: Method, uri: Uri) -> &'static str {
println!("fetching user from database [method={} uri={}]", method, uri);
"User data"
}
That works for one handler and falls apart in a real application. Every handler needs the request metadata as parameters. Every log call inside every helper function needs those values passed down manually. Nested function calls become a maze of parameters that exist only to support logging. If you forget to pass the context into even one function, that function log messages lose their connection to the request.
TraceLayer removes that burden. It wraps every request in a structure called a span, and any log message emitted inside that span automatically picks up the request context. You write tracing::info!("fetching user") in your handler, and the output automatically includes the method, URI, and other request details. You never pass request metadata around manually.
Spans, Events, and Subscribers
Before using TraceLayer, it helps to understand the three ideas it relies on. A span is a record of a unit of work with a start time and an end time. When your server receives an HTTP request, TraceLayer opens a span for that request. The span stays open while your handler runs and closes when the response is sent. While a span is open, any log message you produce gets linked to it automatically.
An event is a single log message at a specific moment. When you write tracing::info!("user logged in"), you are emitting an event. An event has a timestamp, a message, and whatever context is available at that moment.
A subscriber is the component that receives spans and events and decides what to do with them. It might print them to the terminal, write them to a file, send them to a monitoring service, or ignore them entirely. If no subscriber is active, all spans and events are silently discarded. That is why the setup on this page includes initialising a subscriber, and why forgetting it is the first thing to check when nothing appears.
A mental model that helps most beginners is a name tag at a conference. The span is the name tag for a group, and every log event wears the name tag of its group. When you read the log output later, the name tag tells you which group each message belonged to. TraceLayer puts a name tag on every log message produced while handling a request, without you writing the tag yourself.
Each event and span also has a level, which is a measure of how urgent or detailed it is. The levels, from most verbose to most urgent, are TRACE, DEBUG, INFO, WARN, and ERROR. A subscriber has a maximum level, and it only prints events at that level or more urgent. That level system is the key to the whole page, because TraceLayer defaults to DEBUG, and the default subscriber maximum is INFO.
TraceLayer does log on its own, at DEBUG level:
TraceLayer is not silent. Its default configuration emits its own events, on_request with the message started processing request, on_response with finished processing request and the latency and status, and on_eos with end of stream. All of those defaults are DEBUG level, while tracing_subscriber::fmt() defaults to a maximum level of INFO, so with a plain subscriber every TraceLayer event is filtered out before it is printed. That is why the setup on this page enables DEBUG explicitly. With DEBUG enabled, you see the started and finished lines even if your handlers contain no tracing calls at all.
Setting Up TraceLayer
The setup has four steps, and each one depends on the previous one being complete. Add the dependencies, initialise a subscriber, add the layer to the router, and run the server to check the output.
Step 1: Add the required dependencies
Open Cargo.toml and add these dependencies:
[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 tower-http crate contains TraceLayer, but you must enable the trace feature explicitly. Without it, the trace module is not compiled and your code fails to compile when you try to import TraceLayer. The tracing crate provides the macros you use inside handlers, such as tracing::info! and tracing::error!. The tracing-subscriber crate provides the subscriber that prints those events to the terminal. The env-filter feature is needed later on this page, when the subscriber is configured from the RUST_LOG environment variable.
Step 2: Initialise a subscriber
At the very beginning of your main function, before building your router, add this line:
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
This creates a subscriber that formats events as human readable text and prints them to standard output. The subscriber is installed globally, which means all tracing macros across your entire application now produce visible output. The .with_max_level(tracing::Level::DEBUG) part is not optional decoration. TraceLayer span and its started and finished events are all DEBUG level, and fmt() on its own defaults to a maximum of INFO. With a plain tracing_subscriber::fmt().init() you would see your handler info lines but no request context and no TraceLayer events at all, as the plain subscriber trap below shows.
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.
Step 3: Add TraceLayer to your router
Apply TraceLayer to your router using the .layer() method:
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
let app = Router::new()
.route("/", get(hello))
.layer(TraceLayer::new_for_http());
TraceLayer::new_for_http() creates a TraceLayer configured with sensible defaults for HTTP servers. The layer creates a span for every incoming request, records the HTTP method, URI, and version, and closes the span when the response is complete. The new_for_http name exists because tower-http also offers new_for_grpc(), which classifies responses using gRPC status codes instead of HTTP status codes. For an Axum HTTP server, new_for_http is the one to use.
Step 4: Run and check the output
Start the server and send a request to it. With the DEBUG subscriber from Step 2, you see TraceLayer own started and finished lines even for a basic handler that returns a plain string and contains no logging calls at all. Add a tracing::info! call inside the handler to see the span context attached to your own events:
async fn hello() -> &'static str {
tracing::info!("hello handler was reached");
"Hello, world!"
}
Run the server with cargo run, then open http://localhost:3000 in a browser or use curl http://localhost:3000. The terminal shows lines like the ones in the basic example below.
The Basic Example and Its Real Output
Here is the complete runnable code that combines all four setup steps.
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))
.route("/users/{id}", get(get_user))
.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 get_user(axum::extract::Path(id): axum::extract::Path<u64>) -> String {
tracing::info!("looking up user by id");
format!("User ID: {}", id)
}
When you run this server and request / once, the terminal shows output like this, verified by running the program. Timestamps and colour codes are omitted here for readability, and the crate name before the handler message varies with your project name.
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. The first line is TraceLayer announcing the request arrived. The second line is the handler own message, with the request context attached in front of it. The third line is TraceLayer announcing the response, with the latency and the status code. The fourth line, end of stream, fires when the response body has finished streaming to the client. The request{method=GET uri=/ version=HTTP/1.1} part at the start of each line is the span. It was added automatically by TraceLayer. You did not write it in any log call.
The uri=/users/42 part is especially valuable when you request /users/42. If a user reports that the user with ID 42 failed to load, you can search your logs for uri=/users/42 and find every log message associated with that specific request, with no guessing involved.
The output above 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.
The Plain Subscriber Trap
The most common TraceLayer surprise is running the exact 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 fmt().init() 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 customisation section 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.
How the Span Context Reaches Nested Functions
The mechanism behind TraceLayer is straightforward. When a request arrives, TraceLayer extracts the HTTP method, URI, and version from the request. It creates a span named request and stores those values as fields inside the span. Then it calls your handler while the span is active. Any tracing macro called while the span is active automatically includes the span fields in its output. You do not need to do anything special inside your handler. The tracing::info! call works exactly the same whether TraceLayer is present or not. The difference is that with TraceLayer, the span context exists and gets printed.
This behaviour extends through nested function calls. If your handler calls a helper function that calls another function that emits a log event, that event still picks up the span context. The span is active for the entire duration of the request, regardless of how deep your call stack goes.
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(checkout))
.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 checkout() -> &'static str {
tracing::info!("checkout started");
process_payment();
tracing::info!("checkout completed");
"Order confirmed"
}
fn process_payment() {
tracing::info!("charging credit card");
update_inventory();
tracing::info!("payment processed");
}
fn update_inventory() {
tracing::info!("reducing item stock");
}
Make a request to / and the terminal shows five lines, each carrying the same request context, even though they come from three different functions at different call depths.
INFO request{method=GET uri=/ version=HTTP/1.1}: checkout started
INFO request{method=GET uri=/ version=HTTP/1.1}: charging credit card
INFO request{method=GET uri=/ version=HTTP/1.1}: reducing item stock
INFO request{method=GET uri=/ version=HTTP/1.1}: payment processed
INFO request{method=GET uri=/ version=HTTP/1.1}: checkout completed
This is the core value of TraceLayer. Context flows through your entire application automatically, without any manual passing of request data. A database helper three calls deep logs with the same method and path as the handler that started the request.
The log crate macros do not see spans:
The log crate provides macros named log::info!, log::warn!, and log::error!. These look similar to tracing::info!, tracing::warn!, 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.
Customising the Span Fields
The default span created by TraceLayer::new_for_http() captures method, URI, and HTTP version. In many applications, you want to capture additional context or use a different span name. The make_span_with method lets you control exactly what the span records. It takes a closure, which is a small function written inline, that receives a reference to the incoming request and returns a span.
Here is an example that renames the span from request to http_request and drops the HTTP version field.
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 trace_layer = TraceLayer::new_for_http()
.make_span_with(|request: &axum::extract::Request| {
tracing::info_span!(
"http_request",
method = %request.method(),
uri = %request.uri(),
)
});
let app = Router::new()
.route("/", get(hello))
.layer(trace_layer);
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 reached");
"Hello, world!"
}
The output now looks like this.
INFO http_request{method=GET uri=/}: hello handler reached
The span name changed from request to http_request, and the version=HTTP/1.1 field is gone. The make_span_with closure receives a reference to the incoming request, which gives you access to the method, URI, headers, and every other part of the request. The percent sign before request.method() and request.uri() tells tracing to use the Display formatting when printing those values. If you used a question mark instead, tracing would use the Debug formatting, which produces slightly different output with quotes around string values. For most logging purposes, the percent sign produces cleaner output.
Adding a Request ID to the Span
One of the most useful customisations is attaching a request ID to every span. Many clients send an x-request-id header so that a single request can be followed across multiple services. TraceLayer can capture that header value and include it in the span, making it appear in every log line for that request.
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 trace_layer = TraceLayer::new_for_http()
.make_span_with(|request: &axum::extract::Request| {
let request_id = request
.headers()
.get("x-request-id")
.and_then(|value| value.to_str().ok())
.unwrap_or("no-request-id");
tracing::info_span!(
"request",
method = %request.method(),
uri = %request.uri(),
request_id = %request_id,
)
});
let app = Router::new()
.route("/", get(hello))
.layer(trace_layer);
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!("handling hello request");
"Hello, world!"
}
Make a request with a custom header, using curl -H "x-request-id: abc-123" http://127.0.0.1:3000, and the output includes the request ID.
INFO request{method=GET uri=/ request_id=abc-123}: handling hello request
If a request arrives without the header, the unwrap_or fallback supplies the value no-request-id instead, so the field is always present and always searchable. The percent sign before request_id uses the Display formatting, so the value prints without quotes, the same as the method and the URI. Without it, tracing would use the Debug formatting and the value would print with quotes around it. This pattern is widely used in production systems because it lets you correlate logs across multiple services. When one service calls another, both services log the same request ID, and you can search your log tool for that ID to see the complete journey of a single request.
Raising the Span Level with DefaultMakeSpan
The second fix for the plain subscriber trap uses DefaultMakeSpan, which is 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, and include_headers adds the request headers as a span field.
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 fmt().init() subscriber, whose maximum is INFO, 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.
Be careful with include_headers(true). It records every request header inside the span, including authorization headers. If your logs are stored anywhere other people can read, that can leak secrets. Only enable it when you need header values in the logs and you know where the logs go.
Logging When Requests Arrive and Responses Complete
TraceLayer provides two hooks that fire at specific points in the request lifecycle. The on_request callback runs when the request first arrives, before your handler executes. The on_response callback runs after your handler produces a response, and it also receives the latency, which is how long the request took from start to finish. Both callbacks receive the span as their last argument, and the underscore prefix on _span means the parameter is required by the callback signature but not used in the body.
use axum::{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 trace_layer = TraceLayer::new_for_http()
.on_request(|request: &axum::extract::Request, _span: &tracing::Span| {
tracing::info!("received {} request to {}", request.method(), request.uri());
})
.on_response(
|response: &axum::response::Response,
latency: Duration,
_span: &tracing::Span| {
tracing::info!(
"completed with status {} in {:?}",
response.status(),
latency
);
},
);
let app = Router::new()
.route("/", get(hello))
.layer(trace_layer);
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!("inside the handler");
"Hello, world!"
}
When you make a request, you see three log lines in order. The on_request callback fires first, then your handler runs and produces its own log event, and finally on_response fires with the status code and latency.
INFO request{method=GET uri=/ version=HTTP/1.1}: received GET request to /
INFO request{method=GET uri=/ version=HTTP/1.1}: inside the handler
INFO request{method=GET uri=/ version=HTTP/1.1}: completed with status 200 OK in 1.23ms
The latency value is measured from when the span was created to when the response was produced, so it includes the full time your handler took to run. The exact number varies from request to request, and the 1.23ms shown here is an example of the shape, not a value to expect. What matters is that the number is there, in a field you can search and graph.
Using the Built-in Callbacks Instead of Closures
Writing closures for on_request and on_response is flexible, and it is also more code than many applications need. Tower-http ships built-in callback types, DefaultOnRequest and DefaultOnResponse, that do the standard thing with a few settings. The level method changes the level of the event they emit, latency_unit changes how the latency is printed, and include_headers adds the response headers to the event.
use tower_http::{
trace::{DefaultOnResponse, TraceLayer},
LatencyUnit,
};
use tracing::Level;
let trace_layer = TraceLayer::new_for_http().on_response(
DefaultOnResponse::new()
.level(Level::INFO)
.latency_unit(LatencyUnit::Micros),
);
Drop this layer into the basic example in place of the plain TraceLayer::new_for_http() line, with a plain fmt().init() subscriber. With this layer, every response produces an INFO line with the latency in microseconds, even with a plain INFO subscriber, because the event level is INFO now. The built-in version is the right choice when the standard message, finished processing request with latency and status, is what you want, and you only need to change its level or its units. The closure version is the right choice when the message itself needs to change, for example when you want to log different levels for success and failure.
Handling Errors Differently
When a request fails, you usually want to log it more prominently than a successful request. The simplest approach is to check the response status inside on_response and emit different log levels based on the outcome.
use axum::{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 trace_layer = TraceLayer::new_for_http().on_response(
|response: &axum::response::Response,
latency: Duration,
_span: &tracing::Span| {
let status = response.status();
if status.is_server_error() {
tracing::error!("server error - status {} in {:?}", status, latency);
} else if status.is_client_error() {
tracing::warn!("client error - status {} in {:?}", status, latency);
} else {
tracing::info!("success - status {} in {:?}", status, latency);
}
},
);
let app = Router::new()
.route("/", get(success_handler))
.route("/not-found", get(not_found_handler))
.route("/error", get(error_handler))
.layer(trace_layer);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn success_handler() -> &'static str {
"This works"
}
async fn not_found_handler() -> axum::http::StatusCode {
axum::http::StatusCode::NOT_FOUND
}
async fn error_handler() -> axum::http::StatusCode {
axum::http::StatusCode::INTERNAL_SERVER_ERROR
}
Now three requests produce three different levels. A GET to / logs an INFO line with status 200 OK. A GET to /not-found logs a WARN line with status 404 Not Found. A GET to /error logs an ERROR line with status 500 Internal Server Error. Using error for server errors and warn for client errors creates a natural priority system in your logs. Monitoring tools can alert on error level events while treating warn events as less urgent. A 404 is usually not a crisis, because someone requested a missing resource. A 500 means your code broke, and that is worth waking someone up for.
The Failure Callback
There is one more callback, on_failure, which fires when the response is classified as a failure. Classification is TraceLayer way of deciding what counts as a failure, and new_for_http classifies any 5xx status as a failure. The callback receives the failure classification, the latency, and the span. The span reference lets you record a field that was not known when the span was created, using span.record. A field can only be recorded if the span was created with that field present, even as an empty placeholder, which is what tracing::field::Empty does in the example below.
use axum::{body::Body, http::Request, routing::get, Router};
use std::time::Duration;
use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer};
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let trace_layer = TraceLayer::new_for_http()
.make_span_with(|request: &Request<Body>| {
tracing::info_span!(
"request",
method = %request.method(),
uri = %request.uri(),
status_code = tracing::field::Empty,
)
})
.on_failure(
|_failure: ServerErrorsFailureClass,
latency: Duration,
span: &tracing::Span| {
tracing::error!("request failed after {:?}", latency);
span.record("status_code", 500);
},
);
let app = Router::new()
.route("/", get(hello))
.route("/error", get(error_handler))
.layer(trace_layer);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
"Hello, world!"
}
async fn error_handler() -> axum::http::StatusCode {
axum::http::StatusCode::INTERNAL_SERVER_ERROR
}
The example includes a second route, /error, that returns a 500 status, so the callback can be seen firing. Request /error and the callback runs, because a 500 status is classified as a failure. The terminal shows the started and finished lines, then the failure line from the callback.
DEBUG request{method=GET uri=/error}: tower_http::trace::on_request: started processing request
DEBUG request{method=GET uri=/error}: tower_http::trace::on_response: finished processing request latency=0 ms status=500
ERROR request{method=GET uri=/error}: request failed after 271.538µs
The latency in the failure line is an example of the shape, not a value to expect. Request / and nothing extra appears, because a 200 status is not a failure and the callback stays silent.
The on_failure callback runs in addition to on_response, not instead of it. Use on_response for the normal per-request line, and on_failure for the extra work a failure deserves, such as recording the status on the span or sending the failure to an alerting system. The on_eos and on_body_chunk callbacks exist for the same reason at the end of the body stream and for each body chunk, and they are rarely needed in a typical Axum application, because the response is usually a single complete body rather than a long stream.
Controlling What Gets Logged with Levels and Filters
Every tracing macro has a level attached to it, from TRACE at the most verbose end to ERROR at the most urgent end. A plain tracing_subscriber::fmt().init() subscriber prints everything at INFO level and above, which means TRACE and DEBUG events are hidden, including all of TraceLayer defaults. The examples earlier on this page use .with_max_level(tracing::Level::DEBUG) precisely so those events are visible.
You can control which levels appear by configuring the subscriber with an environment filter. The env-filter feature in tracing-subscriber lets you set the filtering level using the RUST_LOG environment variable at runtime, without changing any code. The Cargo.toml in the setup section already enables that feature.
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
The try_from_default_env call reads the RUST_LOG environment variable. If it is not set, the fallback filter of info is used, meaning only INFO, WARN, and ERROR events appear. Run the server normally with cargo run and events at INFO and above appear. Run it with RUST_LOG=debug cargo run and events at DEBUG and above appear, including the TraceLayer started and finished lines. Run it with RUST_LOG=trace cargo run and every event appears, including the most verbose TRACE calls. Be careful with trace in production. It can flood your terminal with far more lines than you can read, making it impossible to find anything useful.
You can also set different levels for different parts of your application. The filter accepts a comma separated list of crate name and level pairs.
RUST_LOG=my_app=debug,tower_http=warn cargo run
This shows DEBUG level events from your own crate but only WARN and ERROR from tower_http. That granularity lets you debug your own code without being overwhelmed by verbose logs from dependencies you did not write. Replace my_app with your own crate name, which is the name field in your Cargo.toml, with hyphens turned into underscores.
Choosing an Output Format
The tracing subscriber can produce output in two main formats, and you pick one when you initialise it. Human readable text is the default and is best for development. JSON output is better for production systems where logs are collected by tools that parse structured data. You follow one path or the other, not both at once.
The default format prints clean, readable lines:
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
Output looks like:
INFO request{method=GET uri=/ version=HTTP/1.1}: handler reached
This is the best choice while developing because the output is easy to scan by eye.
Common Mistakes and How to Fix Them
Forgetting to initialise the subscriber, or initialising it with the wrong maximum level, is the first trap. All tracing macros silently do nothing when no subscriber is active. The compiler does not warn about this, and your server runs fine, you simply see no logs. Always call tracing_subscriber::fmt().init() at the start of main before building your router. And remember that a plain fmt().init() caps output at INFO. Your handler info lines will appear, but TraceLayer DEBUG span and events will not. Enable DEBUG with .with_max_level(tracing::Level::DEBUG) when you want the request context, or raise the span level with DefaultMakeSpan when you want the context without the DEBUG lines.
Using log macros instead of tracing macros is the second trap. The log crate and the tracing crate both define macros with the same names, but they are different crates with different behaviour. log::info! does not know about spans, so it will not pick up TraceLayer request context. Use tracing::info! and friends.
Forgetting the trace feature in tower-http is the third trap. The tower-http crate is modular, and TraceLayer lives behind the trace feature flag. If your Cargo.toml has tower-http = "0.7" without the feature, the import use tower_http::trace::TraceLayer will fail to compile. Add features = ["trace"] to the dependency.
Applying TraceLayer to an empty router is the fourth trap. The .layer() method applies middleware to all routes that were registered before the layer call. 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.
Over-verbose logging is the fifth trap. Setting RUST_LOG=trace for every crate in your project produces enormous log output. Each HTTP request can generate dozens of trace events, quickly making logs unreadable. Start with info as the default, raise individual crates to debug only when investigating a specific problem.
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.
Summary
TraceLayer solves a specific and universal problem. When a server handles many requests at once, plain log messages lose their connection to the requests that produced them. By wrapping each request in a tracing span, TraceLayer makes sure that every event emitted during request handling carries the method, URI, and other request metadata automatically.
The decision framework 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 and the started and finished lines. When the application goes to production, make a choice. 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.