HTTP Request Spans
Learn how TraceLayer builds one span per HTTP request, what fields the span carries, and how to shape it with make_span_with
A request span is the record TraceLayer opens for one HTTP request. It has a name, a level, and a small set of fields, and it stays open from the moment the request arrives until the response body has finished streaming. Every log event produced while the span is open carries the span fields in front of it, so the span is what turns a pile of separate log lines into a story about one request. This page is about that span: what it carries by default, how to change its fields, how to change its level, and how to add information to it after it was created.
Where This Fits
A log line without context tells you that something happened. A log line inside a request span tells you which request it happened for, which path was called, and which method was used. The span is the mechanism that attaches that context. The layer creates it, your handler runs inside it, and the subscriber prints it. Once you understand the span, the rest of TraceLayer becomes a set of choices about what the span should carry and when it should be visible.
The Smallest Working Version
Here is the smallest server that shows the default span. It is the same shape as the TraceLayer setup, with one route and one log call inside the handler.
[package]
name = "span_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"] }
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)
}
The subscriber line matters here as much as the layer line. The default span is DEBUG level, and a plain fmt() subscriber only shows INFO and above, so with a plain subscriber the span is disabled and no context appears at all. Run the server with cargo run, then request both routes.
curl http://127.0.0.1:3000/
curl http://127.0.0.1:3000/users/42
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
Requesting /users/42 produces the same four lines with a different uri field.
INFO request{method=GET uri=/users/42 version=HTTP/1.1}: looking up user by id
The uri=/users/42 part is the piece that makes the span useful in practice. 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 span is the search key, and the URI is the most specific part of it.
The span prefix means the span is open:
If your handler lines show a request{method=... uri=...} prefix, the span is open and active while your handler runs. If the handler lines appear with no prefix, the span is disabled by level, not missing. Check the subscriber maximum level first, and the span level second.
The Three Default Fields
The default span carries exactly three fields, and each one comes straight from the incoming request.
| Field | Value for a typical request | Where it comes from |
|---|---|---|
method | GET | The HTTP method of the request |
uri | /users/42 | The full URI, path plus query string |
version | HTTP/1.1 | The HTTP version the client used |
The span name is request. The name is the word before the opening brace, and it is what you search for when you want every line belonging to any request. The level is DEBUG, which is why the subscriber needs DEBUG enabled for the span to appear at all.
Two details in the default span are worth understanding, because they explain how to build your own span later. The first is the difference between the two formatting marks used when the span is built. The method and the URI are recorded with %, which means Display formatting, the plain human-readable form. The version is recorded with ?, which means Debug formatting. For a version value the two forms print the same text, HTTP/1.1, but the distinction matters for the fields you add yourself, as the request ID example below shows. The second detail is that the URI field holds the full URI, not just the path. A request to /search?q=rust records uri=/search?q=rust, query string included. That is usually what you want for debugging, and it is something to remember if your query strings ever carry sensitive values.
How the Span Reaches Nested Functions
The span is active for the entire duration of the request, regardless of how deep your call stack goes. A handler that calls a helper function that calls another function still logs with the same span context, because the span is entered once by the layer and stays entered until the response is done. No parameter passing is involved. The tracing macros pick up whatever span is active at the moment they run.
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. Only the handler lines are shown here, to keep the focus on the span.
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 the span. 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.
Changing the Span Level with DefaultMakeSpan
DefaultMakeSpan is the built-in span maker that TraceLayer uses by default, and it has two settings: level and include_headers. The level method sets the level of the span itself. The default is DEBUG.
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. 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.
For comparison, here is what the same request looks like with a plain subscriber and the default layer, verified by running the program.
INFO hello handler was reached
No prefix, no context. The handler line is identical in the code, and the only difference is the span level. That contrast is the fastest way to check whether a missing prefix is a span level problem or something else. If raising the span level to INFO brings the prefix back, the level was the problem.
The span level and the event levels are controlled separately. Raising only the on_response level to 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. That was verified by running a server with an INFO on_response and a plain subscriber: the finished line appeared as a bare line with no request{...} prefix. Set the span level when you want context, set the event level when you want the layer own lines, and set both when you want both.
Including Request Headers in the Span
The second DefaultMakeSpan setting is include_headers, which records every request header as a headers field on the span.
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
let trace_layer = TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().include_headers(true));
Drop this into the basic example and request / with curl. The output shows the headers field at the end of the span, verified by running the program.
DEBUG request{method=GET uri=/ version=HTTP/1.1 headers={"host": "127.0.0.1:3000", "user-agent": "curl/8.5.0", "accept": "*/*"}}: tower_http::trace::on_request: started processing request
INFO request{method=GET uri=/ version=HTTP/1.1 headers={"host": "127.0.0.1:3000", "user-agent": "curl/8.5.0", "accept": "*/*"}}: hello handler was reached
Every header appears on every line for that request, because the field lives on the span. That makes the lines long, and it makes them useful for debugging header problems, such as a missing content type or an unexpected user agent. It also makes them dangerous. Headers can carry authorization tokens, cookies, and API keys, and a span field is printed on every line the span covers. If your logs are stored anywhere other people can read, that can leak secrets into storage you do not control.
include_headers records authorization headers too:
include_headers(true) records every request header inside the span, including authorization headers and cookies. 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. For most applications, recording one chosen header by name is safer than recording all of them.
Shaping the Span with make_span_with
DefaultMakeSpan covers the two common settings, level and headers. For anything else, make_span_with takes a closure that receives a reference to the incoming request and returns a span. A closure is a small function written inline. The closure gives you access to the method, URI, headers, and every other part of the request, and you decide the span name and the fields.
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, verified by running the program.
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. Three details in this example deserve attention. The first is the macro name, tracing::info_span!. The span level here is INFO, not DEBUG, because the macro name sets the level. info_span! makes an INFO span, debug_span! makes a DEBUG span, and the default span maker uses DEBUG. The second detail is the % before request.method() and request.uri(). That mark tells tracing to use Display formatting when printing those values, which produces clean text with no quotes. The third detail is the type of the closure argument, &axum::extract::Request. That is the request type Axum uses, and writing it out in full keeps the compiler error messages readable when the closure body is wrong.
The percent sign and the question mark
The % and ? marks in span macros control how a value is printed, and the difference shows up clearly with string values. A field written as request_id = request_id, with no mark, uses Debug formatting, and a string printed with Debug formatting gets quotes around it. A field written as request_id = %request_id uses Display formatting, and the same string prints with no quotes. Both forms were verified by running two servers that differ only in that one mark.
Without the percent sign, the output is:
DEBUG http_request{method=GET uri=/ request_id="abc-123"}: tower_http::trace::on_request: started processing request
With the percent sign, the output is:
DEBUG http_request{method=GET uri=/ request_id=abc-123}: tower_http::trace::on_request: started processing request
The value is the same in both cases. Only the printing differs. For most logging purposes the percent sign produces cleaner output, and the default span uses it for the method and the URI for exactly that reason. Use % for values you want to read as plain text, and ? for values where the Debug form carries information, such as the HTTP version or a header map.
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!(
"http_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, verified by running the program.
INFO http_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. That fallback matters. A field that is sometimes missing is hard to search for, because a search for its absence is not the same as a search for a value. Keeping the field always present, with a clear placeholder value when the header is missing, makes the logs uniform.
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. If the client does not send an ID, a common next step is to generate one inside the closure instead of using a placeholder, but generating IDs belongs to request ID handling rather than to the span itself, so this page keeps the placeholder form.
Recording Fields After the Span Was Created
Some information does not exist when the span is created. The status code is the clearest example. The span opens when the request arrives, and the status only exists once the handler has produced a response. The span.record method adds such a value to the span afterwards, and every log line printed after the recording shows the new field.
Recording has one strict rule. A field can only be recorded if the span was created with that field present, even as an empty placeholder. The placeholder is written as tracing::field::Empty. If the span was created without the field, the recording call is silently ignored, and no error is produced anywhere. That silence is the trap. The code compiles, the server runs, and the field simply never appears.
Here is the pattern done correctly. The span is created with a status_code field holding Empty, and the on_response callback records the real status into it. The callback then hands the response to the default on_response behaviour, so the finished line is still printed. That second step matters, because replacing on_response with a closure replaces the default finished line entirely. Without it, the finished line disappears.
use axum::{routing::get, Router};
use std::time::Duration;
use tower_http::trace::{DefaultOnResponse, OnResponse, 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!(
"request",
method = %request.method(),
uri = %request.uri(),
version = ?request.version(),
status_code = tracing::field::Empty,
)
})
.on_response(
|response: &axum::response::Response,
latency: Duration,
span: &tracing::Span| {
span.record("status_code", response.status().as_u16());
DefaultOnResponse::new().on_response(response, latency, span);
},
);
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 {
tracing::info!("hello handler was reached");
"Hello, world!"
}
async fn error_handler() -> axum::http::StatusCode {
axum::http::StatusCode::INTERNAL_SERVER_ERROR
}
Request / and the output shows the recorded field on the finished line and on the end of stream line, verified by running the program.
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 status_code=200}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
DEBUG request{method=GET uri=/ version=HTTP/1.1 status_code=200}: tower_http::trace::on_eos: end of stream stream_duration=0 ms
The started line and the handler line do not show status_code, because the recording happens later, in on_response. The field appears from the finished line onwards. That ordering is worth remembering. A recorded field is not retroactive. Lines printed before the recording keep the span as it was, and lines printed after it show the new value. Request /error and the same pattern shows status_code=500 on the finished line and on the failure line.
Two mistakes are common here, and both were verified by running servers that make them. The first is recording without the Empty placeholder. The span never shows the field, and nothing warns you. The output looks exactly like the default span, which makes the mistake easy to miss. The second is replacing on_response with a recording closure that does not delegate to DefaultOnResponse. The recording works, and the field appears on the end of stream line, but the finished line vanishes entirely, because the closure replaced the default behaviour instead of adding to it. If the finished line disappears after you add a recording callback, the missing delegation is the cause.
Recorded fields are not retroactive:
A field recorded in on_response appears on the finished line and on every line after it, but not on the started line or on handler lines printed before the recording. If you need a value on every line for a request, it must be known when the span is created, in make_span_with, not recorded later.
Recording from Inside a Handler
A handler can also record a field on its own span, using tracing::Span::current(). That call returns the span that is active at the moment the handler runs, which is the request span. This is useful when the value is known inside the handler but not visible to the layer, such as a user ID loaded from a database.
async fn hello() -> &'static str {
tracing::Span::current().record("status_code", 200);
tracing::info!("hello handler was reached");
"Hello, world!"
}
This works only if the span was created with the field as an Empty placeholder, exactly as in the previous section. The recording in the example above happens before the info! call, so the handler line itself shows the recorded value, verified by running the program.
INFO request{method=GET uri=/ status_code=200}: hello handler was reached
The difference between recording in the handler and recording in on_response is timing and knowledge. The handler knows application values, such as which user was loaded, and can record them early enough for its own log lines to show them. The on_response callback knows response values, such as the status code, and can record them for the lines that come after. Use the handler for values the application computes, and the callback for values the layer computes.
What the Span Does Not Carry
The default span carries the method, the URI, and the version. It does not carry the status code, and it does not carry the latency. Those two values live on the finished event, not on the span, because they do not exist until the response exists. That is a deliberate split. The span holds what is known when the request arrives. The events hold what is learned as the request is handled. The recording pattern above bridges the split for one field at a time, when a value is useful enough to appear on later lines as part of the span. Do not try to put everything on the span. A span with a dozen fields is hard to read, and every field is repeated on every line the span covers.
How a Span Lives and Dies
The life of one request span looks like this, in order.
Request arrives at TraceLayer
|
v
make_span_with creates the span with method, uri, version
|
v
Span is entered: on_request fires, handler runs, handler logs carry the span
|
v
Handler returns a response: on_response fires, span fields can be recorded
|
v
Body streams: on_body_chunk fires per chunk, on_eos fires at the end
|
v
Span closes when the body stream ends
The span closes when the body stream ends, not when the handler returns. That is why the end of stream line still carries the span prefix. Two requests handled at the same time get two separate spans, and their log lines interleave in the terminal, each line wearing the span of its own request. That interleaving is normal, and it is exactly the situation the span exists for. Without it, two concurrent requests would produce one unreadable pile of lines.
Testing It
Testing a custom span means testing that the router still answers correctly with the layer applied, and that the span configuration compiles. 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::{DefaultMakeSpan, TraceLayer};
use tracing::Level;
fn app() -> Router {
Router::new()
.route("/", get(|| async { "Hello, world!" }))
.route("/error", get(|| async { StatusCode::INTERNAL_SERVER_ERROR }))
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO)),
)
}
#[tokio::test]
async fn home_returns_ok_with_custom_span() {
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_with_custom_span() {
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. The equivalent tests passed in the scratch project used to verify this page. The tests prove the custom span layer does not change what the routes return. The span fields themselves are checked by eye, by running the server and curling it, which is how every output block on this page was produced.
Common Beginner Mistakes
Recording a field the span does not declare
// Wrong - silently ignored, the field never appears
tracing::info_span!(
"request",
method = %request.method(),
uri = %request.uri(),
)
A later span.record("status_code", 200) call against this span does nothing. The recording needs a placeholder field created with tracing::field::Empty, and without it the call is silently ignored. The fix is to add status_code = tracing::field::Empty to the span. The silence is what makes this mistake expensive. The code compiles, the server runs, and the only symptom is a missing field in the logs.
Replacing on_response without delegating
A custom on_response closure replaces the default finished line. If the closure only records a field and returns, the finished line disappears. The fix is to call DefaultOnResponse::new().on_response(response, latency, span) inside the closure after recording, which prints the finished line with the recorded field now visible on the span. The OnResponse trait must be imported for that call to resolve.
Using Debug formatting for readable strings
A field written without a mark, such as request_id = request_id, prints string values with quotes, because it uses Debug formatting. That is not an error, but it makes logs harder to scan and harder to search, because a search for request_id=abc-123 will not match request_id="abc-123". Use request_id = %request_id for values you want to read and search as plain text.
Including all headers in production logs
include_headers(true) is a debugging aid, not a default. It records authorization headers and cookies into every log line for the request. In development, on a local machine, that is harmless. In production, where logs are shipped to storage other people can read, it can leak secrets. Record one chosen header by name instead, as the request ID example does.
Expecting the span to show the status
The default span has no status field, and no span does until you add one with the recording pattern. The status lives on the finished event. If your logs show the status on the finished line but not on the handler lines, that is the design working as intended, not a missing configuration.
Final Complete Example
Here is everything from this page put together. One server, a custom span with a request ID and a recorded status code, and routes that show the difference between a success and a failure.
use axum::{http::StatusCode, routing::get, Router};
use std::time::Duration;
use tower_http::trace::{DefaultOnResponse, OnResponse, 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!(
"http_request",
method = %request.method(),
uri = %request.uri(),
request_id = %request_id,
status_code = tracing::field::Empty,
)
})
.on_response(
|response: &axum::response::Response,
latency: Duration,
span: &tracing::Span| {
span.record("status_code", response.status().as_u16());
DefaultOnResponse::new().on_response(response, latency, span);
},
);
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();
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 error_handler() -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
[package]
name = "span_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.
curl http://127.0.0.1:3000/
curl -H "x-request-id: abc-123" http://127.0.0.1:3000/
curl http://127.0.0.1:3000/error
The first request shows request_id=no-request-id and status_code=200 on its later lines. The second shows request_id=abc-123. The third shows status_code=500 on its finished and failure lines. Each line for a request carries the same span, so searching for one request ID finds the whole story of that request.
Summary
The span is the unit of identity in request tracing, and the decision framework for shaping it has three questions. First, what must every line for a request show. The defaults answer that with method, URI, and version, and a request ID is the most common addition. Second, when must the span be visible. DEBUG shows everything while you learn, and INFO with a plain subscriber shows the context without the layer own lines in production. Third, what is learned too late to put on the span at creation. Those values are recorded later, with an Empty placeholder declared up front and a delegation to the default behaviour so nothing the layer normally prints goes missing. Answer those three questions and the span carries exactly what the reader of the logs needs, on every line, with nothing extra repeated a hundred times a request.