HTTP Status Fields

Learn how TraceLayer records the response status code, what counts as a failure, and how to put the status on the request span

The status field is the number at the end of the finished line that says what the response was: status=200 for a success, status=404 for a missing page, status=500 for a broken handler. It is the smallest field on the line and the one you search first when something goes wrong, because it sorts every request into success or failure at a glance. This page explains where that number comes from, what counts as a failure, how to change that rule, and how to put the status on the request span so it appears on every line for the request, not only on the finished line.

Where This Fits

Every finished line ends with two fields, a latency and a status. The latency says how long the request took, and the status says what it produced. The two fields sit side by side because they answer the two halves of the same question: how long, and with what result. This page takes the second half apart, and it also takes apart the failure line that appears next to the finished line when the status is a server error.

The Smallest Working Version

Here is the smallest server that makes the status field visible. It has four routes, each returning a different status, so the field can be seen changing.

Cargo.toml
[package]
name = "status_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"] }
src/main.rs
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("/created", get(created))
        .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();
    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 created() -> (StatusCode, &'static str) {
    (StatusCode::CREATED, "Created")
}

async fn not_found() -> StatusCode {
    StatusCode::NOT_FOUND
}

async fn error_handler() -> StatusCode {
    StatusCode::INTERNAL_SERVER_ERROR
}

Run the server with cargo run, then request each route.

curl http://127.0.0.1:3000/
curl http://127.0.0.1:3000/created
curl http://127.0.0.1:3000/not-found
curl http://127.0.0.1:3000/error

The finished lines look like this, 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_response: finished processing request latency=0 ms status=200
DEBUG request{method=GET uri=/created version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=201
DEBUG request{method=GET uri=/not-found version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=404
DEBUG request{method=GET uri=/error version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=500

The status field changes with the route, and nothing else on the line changes shape. A 201 for a created resource, a 404 for a missing one, a 500 for a broken one. The field is always a plain number, never text like 200 OK. The reason text is the status code the handler returned, and the layer records that code exactly as the response carries it.

Four statuses means the field works:

If the finished lines show status=200, status=201, status=404, and status=500 for the four routes, the status field is working. The numbers come from the responses themselves, so a wrong number here means the handler returned the wrong status, not that the layer misread it.

The Status Field, Exactly

The field is named status, and its value is the HTTP status code as a number. That name matters, because other tracing systems use different names for the same idea. Some use http.status_code, which is the name from the OpenTelemetry conventions. Tower-http does not use that name. Its default finished event records the field as status, and searching your logs for http.status_code will find nothing. Search for status=500 instead.

The value is a number, not text. The finished line prints status=200, not status=200 OK. That makes the field easy to filter and to graph. A log tool can count how many lines have status=500 without parsing words out of a sentence. The number is the status code of the response as the handler produced it. If the handler returns a 404, the field reads 404. If a route does not exist at all, Axum itself returns a 404, and the field reads 404 for that too, because the layer sees the response Axum produced.

The status field lives on the finished event, not on the span. The span is created when the request arrives, and the status does not exist yet at that point. Only the finished event, which fires after the response exists, can carry it. That split is why the handler lines for a request never show the status by default. Putting the status on the span needs the recording pattern shown later on this page.

In JSON output, the same field appears as a JSON number inside the event fields. Running the basic server with a JSON subscriber produces lines like this, verified by running the program. The timestamp and the crate name will differ in your own application.

{"timestamp":"2026-11-14T11:48:58.088421Z","level":"DEBUG","fields":{"message":"finished processing request","latency":"0 ms","status":200},"target":"tower_http::trace::on_response","span":{"method":"GET","uri":"/","version":"HTTP/1.1","name":"request"},"spans":[{"method":"GET","uri":"/","version":"HTTP/1.1","name":"request"}]}

The "status":200 value is a JSON number, while the "latency":"0 ms" value is a JSON string. That difference is useful. A log tool can filter on the status as a number, comparing it with greater-than and less-than, while the latency needs parsing first. The span object in the same line carries the method, URI, and version, which is the JSON form of the span prefix from the text output.

To use JSON output, add the json feature to tracing-subscriber and call .json() on the subscriber builder. The json feature is what makes the .json() method exist at all. Without it, the method call fails to compile.

src/main.rs
tracing_subscriber::fmt()
    .json()
    .with_max_level(tracing::Level::DEBUG)
    .init();
Cargo.toml
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }

What Counts as a Failure

TraceLayer::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, 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.

Request /error and the output gains a 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.

A 404 does not produce a failure line. It is a client error, not a server error, and the default classifier does not treat it as a failure. Request /not-found and you see only the finished line with status=404. Beginners often expect the failure line for any error status, and its absence for a 404 looks like a bug. It is the rule working as designed. The classifier only counts 5xx as failures, and the next section shows how to change that rule when a different rule fits the application.

The on_failure callback also fires when the inner service itself returns an error, rather than a response, and when the body stream fails partway through. Those cases are rarer in an Axum application, where handlers return responses rather than errors, but the callback covers them the same way. The failure classification it receives describes what went wrong, and the latency it receives is the same request latency.

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.

Changing What Counts as a Failure

The classifier is the part of the layer that decides whether a response is a failure. new_for_http builds the layer with a classifier that treats 5xx as failures. TraceLayer::new(...) builds the layer with a classifier you supply. The tower_http::classify module provides ready-made classifiers, and StatusInRangeAsFailures is the one that treats a range of status codes as failures.

The example below treats every 4xx and 5xx status as a failure, so a 404 now produces a failure line.

src/main.rs
use axum::{http::StatusCode, routing::get, Router};
use tower_http::{
    classify::StatusInRangeAsFailures,
    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(
            StatusInRangeAsFailures::new(400..=599).into_make_classifier(),
        ));

    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 /not-found and the output now has the failure line, verified by running the program.

DEBUG request{method=GET uri=/not-found version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=404
ERROR request{method=GET uri=/not-found version=HTTP/1.1}: tower_http::trace::on_failure: response failed classification=Status code: 404 Not Found latency=0 ms

The range 400..=599 is inclusive at both ends, so it covers every client error and every server error, and nothing else. A 200 still produces no failure line, and a 301 still produces no failure line. The into_make_classifier call turns the classifier into the form TraceLayer::new expects. That call is easy to forget, and without it the types do not line up and the code fails to compile.

Changing the classifier changes only the failure decision. The finished line is unchanged, the span is unchanged, and the status field still reads the same number. That separation is worth keeping in mind. The classifier decides what the layer calls a failure. It does not change what the response was.

Think carefully before widening the failure range. A 404 is often not a failure of your code. It is usually a client asking for something that does not exist, a mistyped link, or a search engine following an old URL. Treating every 404 as a failure at ERROR level can flood an alerting system with noise that nobody acts on, and real 500 errors get buried in it. A common middle ground is to keep the default 5xx rule for alerting, and to watch the 404 count separately, from the finished lines, where the status field is already available for counting.

Changing the Failure Level

The default on_failure logs at ERROR level. DefaultOnFailure has a level method that changes that, without changing anything else about the failure line.

src/main.rs
use tower_http::trace::{DefaultOnFailure, TraceLayer};
use tracing::Level;

let trace_layer = TraceLayer::new_for_http()
    .on_failure(DefaultOnFailure::new().level(Level::WARN));

Drop this layer into the basic example and request /error. The failure line now appears at WARN instead of ERROR, verified by running the program.

WARN 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 message, the classification, and the latency are all unchanged. Only the level moved. That makes the level setting a good fit for a service where 500 responses are common enough that ERROR level alerting would be noise, but rare enough that they still deserve a visible line. The failure line is still there, and a log tool can still count it, but it no longer triggers an ERROR alert.

Branching on Status in on_response

Sometimes the right response to a status is not a different classifier but a different log level per status class, inside the on_response callback itself. A custom on_response closure receives the response, so it can read the status and choose the level. Server errors log at ERROR, client errors at WARN, and successes at INFO.

src/main.rs
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 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(hello))
        .route("/not-found", get(not_found))
        .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 not_found() -> StatusCode {
    StatusCode::NOT_FOUND
}

async fn error_handler() -> StatusCode {
    StatusCode::INTERNAL_SERVER_ERROR
}

Three requests produce three different levels, verified by running the program. 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, and the default failure line follows it, because the classifier still treats the 500 as a failure.

INFO request{method=GET uri=/ version=HTTP/1.1}: success - status 200 OK in 333.07us
WARN request{method=GET uri=/not-found version=HTTP/1.1}: client error - status 404 Not Found in 178.959us
ERROR request{method=GET uri=/error version=HTTP/1.1}: server error - status 500 Internal Server Error in 185.919us

The pages write us where your terminal prints a Greek letter:

The durations above print with us for microseconds. On a real terminal, the same durations print with the Greek letter mu before the s. These pages write us instead, so the text stays plain ASCII. The number is the same either way.

The is_server_error and is_client_error methods come from the http crate, which Axum re-exports as axum::http::StatusCode. They check the status class by number range, 5xx and 4xx, so the branching matches the classifier ranges a reader already knows. The {:?} formatting on the latency prints the full duration, such as 333.07us, instead of the rounded millisecond form. Using ERROR for server errors and WARN for client errors creates a natural priority system in the 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 the code broke, and that is worth waking someone up for.

One warning applies to every custom on_response closure. Replacing on_response replaces the default finished line entirely. The closure above prints its own line instead, so nothing is lost, but a closure that only records a value and prints nothing will make the finished line disappear. If the finished line vanishes after you add a custom callback, the callback replaced the default instead of adding to it.

Recording the Status on the Span

The status lives on the finished event by default. To make it appear on every line for the request, including lines printed after the response exists, record it on the span. The pattern needs two parts. The span is created with a status_code field holding an Empty placeholder, 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.

src/main.rs
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| {
            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() -> StatusCode {
    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.

The OnResponse trait import is what makes the delegation call work. DefaultOnResponse::new().on_response(response, latency, span) calls the default behaviour as a plain method, and that method needs the trait in scope to resolve. Without the import, the compiler reports that no method named on_response exists, which is the clue to add the import rather than to change the call.

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 was created with only method and URI, and a later span.record("status_code", 200) call was silently ignored. The output looked exactly like the default span, with no error anywhere. The fix is to declare the field with tracing::field::Empty when the span is created. The second mistake is replacing on_response with a recording closure that does not delegate to DefaultOnResponse. The recording worked, and the field appeared on the end of stream line, but the finished line vanished entirely, because the closure replaced the default behaviour instead of adding to it.

Recording without a placeholder is silently ignored:

A field can only be recorded if the span was created with that field present, even as an empty placeholder. If the span was created without the field, span.record does nothing, and no error is produced anywhere. The code compiles, the server runs, and the field simply never appears. Always declare a field you plan to record with tracing::field::Empty in make_span_with.

Recording from inside a handler

A handler can also record the status 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 handler knows the status it is about to return, and wants its own log lines to show it.

src/main.rs
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 above. The recording in this example 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 and can record them early enough for its own log lines to show them. The on_response callback knows the real response status for every route, including routes whose handlers return errors, and can record it for the lines that come after. Use the handler for values the application computes, and the callback for the response status itself, which the layer sees for every request without any help from the handler.

The gRPC Status

TraceLayer::new_for_grpc() is the constructor for services that speak gRPC, and it reads the status differently. For gRPC traffic, the status is not the HTTP status code. It is the gRPC status code carried in the grpc-status header or trailer, where 0 means success and any other number names the failure. The finished event still records the field as status, but the number it holds is the gRPC code, not the HTTP code. A successful gRPC call logs status=0.

For a plain HTTP server, new_for_http is the right constructor, and a non-gRPC response falls back to its HTTP status. That fallback was verified by running a plain HTTP server with new_for_grpc(): a request still logged status=200, because the response carried no gRPC content type. That does not make the gRPC constructor a good choice for an HTTP server. Its failure classification follows gRPC rules, so use new_for_http unless the service actually speaks gRPC. One more detail comes from the layer source rather than from a live run, because no gRPC server was run for this page. For a streaming gRPC response, the status does not exist yet when the response headers arrive, so the finished event carries no status field at all. The status appears later, on the end of stream event, once the trailers arrive.

How Status, Classification, and the Span Fit Together

The three ideas on this page relate to each other in one flow, in order.

Handler returns a response with a status code
        |
        v
on_response fires: finished line prints latency and status
        |
        v
Classifier checks the status: 5xx is a failure by default
        |
        v
Failure: on_failure fires at ERROR with the classification and latency
        |
        v
Recording callback writes the status onto the span as status_code
        |
        v
Later lines, end of stream and failure, carry status_code in the span

The status starts as a property of the response, becomes a field on the finished event, decides the failure classification, and can optionally become a field on the span. Each step is separate, and each step can be changed separately. The classifier can change without touching the finished line. The recording can change without touching the classifier. The level of the failure line can change without touching either. That separation is what makes the layer easy to tune. One setting changes one behaviour, and the rest stays as it was.

Testing It

Testing status handling means testing that the routes return the statuses they promise, 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.

tests/status_test.rs
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("/created", get(|| async { (StatusCode::CREATED, "Created") }))
        .route("/not-found", get(|| async { StatusCode::NOT_FOUND }))
        .route("/error", get(|| async { StatusCode::INTERNAL_SERVER_ERROR }))
        .layer(TraceLayer::new_for_http())
}

#[tokio::test]
async fn home_returns_200() {
    let response = app()
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn created_returns_201() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/created")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn not_found_returns_404() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/not-found")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn error_returns_500() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/error")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
Cargo.toml
[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 layer does not change what the routes return, and they prove each route returns the status the finished line reports. The log lines 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

Searching for http.status_code

The finished event records the field as status, not http.status_code. The longer name belongs to other tracing systems, and searching for it in tower-http logs finds nothing. Search for status=500 in text logs, or filter on the status number in JSON logs.

Expecting a 404 to trigger on_failure

A 404 is a client error, and the default classifier does not treat it as a failure, so no failure line appears for it. The classifier rule is 5xx only. If 404 responses need a failure line, the rule must be changed deliberately with a custom classifier, and the alerting cost of that change should be weighed first.

Expecting the status on the span by default

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 the 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.

Recording without a placeholder

A span.record call against a span that was not created with the field is silently ignored. The code compiles, the server runs, and the field never appears. Always declare a field you plan to record with tracing::field::Empty in make_span_with, and check the finished line for the field after adding a recording callback.

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, taking its latency and status fields with it. Add a log call inside the closure, or delegate to DefaultOnResponse after recording, so the finished line is still printed.

Widening the failure range widens the alerts:

Treating 4xx responses as failures makes every mistyped link and every old search engine URL produce an ERROR failure line. That noise can bury real 500 errors in an alerting system. Keep the default 5xx rule for alerting unless the application genuinely treats a 404 as its own failure, and watch the 404 count from the finished lines instead.

Final Complete Example

Here is everything from this page put together. One server, four routes, a custom classifier that treats 4xx and 5xx as failures, a recorded status on the span, and a failure level of WARN.

src/main.rs
use axum::{http::StatusCode, routing::get, Router};
use std::time::Duration;
use tower_http::{
    classify::StatusInRangeAsFailures,
    trace::{DefaultOnFailure, DefaultOnResponse, OnResponse, TraceLayer},
};
use tracing::Level;

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();

    let trace_layer = TraceLayer::new(
        StatusInRangeAsFailures::new(400..=599).into_make_classifier(),
    )
    .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);
        },
    )
    .on_failure(DefaultOnFailure::new().level(Level::WARN));

    let app = Router::new()
        .route("/", get(hello))
        .route("/created", get(created))
        .route("/not-found", get(not_found))
        .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 created() -> (StatusCode, &'static str) {
    (StatusCode::CREATED, "Created")
}

async fn not_found() -> StatusCode {
    StatusCode::NOT_FOUND
}

async fn error_handler() -> StatusCode {
    StatusCode::INTERNAL_SERVER_ERROR
}
Cargo.toml
[package]
name = "status_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 http://127.0.0.1:3000/created
curl http://127.0.0.1:3000/not-found
curl http://127.0.0.1:3000/error

The / and /created requests show status_code=200 and status_code=201 on their later lines, with no failure line. The /not-found request shows status_code=404 and a WARN failure line, because the custom classifier treats 404 as a failure. The /error request shows status_code=500 and a WARN failure line, because the failure level was lowered from ERROR to WARN. Each setting on the layer changed exactly one behaviour, and the rest stayed as it was.

Summary

The status field answers one question, what did the request produce, and the decision framework for using it has three choices. First, read the field where it lives. The finished event carries status as a number, and the span does not carry it until you record it there. Second, decide what counts as a failure. The default rule is 5xx only, which keeps 404 noise out of the alerts, and widening it to 4xx is a deliberate trade between catching client errors and flooding the failure lines. Third, decide how failures should sound. The default failure line is ERROR, a custom on_response can branch by status class, and DefaultOnFailure can lower the level to WARN. The status is a small number, but those three choices decide whether the logs whisper, speak, or shout when a request goes wrong.