Request Logging Middleware in Axum

Learn how to log HTTP requests in Axum with tower-http TraceLayer and custom from_fn logging middleware, with complete beginner examples and explanations

Every time a request hits your server, you probably want to know what happened. Which path was called? Did it succeed? How long did it take? Request logging middleware answers those questions. It sits between the network and your handler, records the details, and passes the request along.

In Axum, you have two ways to add request logging. The easiest is the ready-made TraceLayer from the tower-http crate, which produces structured logs with almost no code. The other is writing your own middleware as an async function, which gives you full control over the log format and the data you collect. This page walks through both, starting with the simplest setup.

What Request Logging Middleware Does

A web server receives requests and sends back responses. Without logging, you only see what you explicitly print inside your handlers. Failed requests, slow routes, and unexpected methods stay invisible, and debugging a problem in production becomes guesswork.

Request logging middleware solves this by running code around every request. It can record the HTTP method, the path, the status code of the response, and how long the whole thing took. You write the logging logic once, and it applies to every route you attach it to.

In Axum, middleware is attached with .layer() on a Router. The layer wraps the router, intercepts requests on the way in, and intercepts responses on the way out. A logging layer does its work at those two moments, once when the request arrives and once when the response is ready.

The Easiest Way, Using TraceLayer

The tower-http crate provides TraceLayer, a production-ready logging layer built on the tracing ecosystem. tracing is the Rust library for structured diagnostic output. It emits events, which are named log records with attached fields, and a subscriber decides how those events are printed. TraceLayer emits the events. You install a subscriber to see them.

Setting it up takes three pieces, and each one depends on the one before it. The dependencies must exist before the subscriber code can compile. The subscriber must be installed before the server starts, or the events go nowhere. The layer must be attached to the router before the router starts serving.

Cargo.toml
[package]
name = "logging-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tower-http = { version = "=0.7.1", features = ["trace"] }
src/main.rs
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

async fn hello() -> &'static str {
    "Hello, world!"
}

#[tokio::main]
async fn main() {
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "logging_demo=info,tower_http=debug".into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();
    let app = Router::new()
        .route("/", get(hello))
        .layer(TraceLayer::new_for_http());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

TraceLayer::new_for_http() creates a layer configured for HTTP services. It opens a tracing span for each request and emits events when the request arrives and when the response is produced. The EnvFilter checks the RUST_LOG environment variable first. When it is not set, the fallback string "logging_demo=info,tower_http=debug" is used. That string means your own crate logs at info level, while the tower_http crate logs at debug level, which is where TraceLayer sends its request and response events by default. The package name in the fallback must match the name in your Cargo.toml, which is logging-demo here, written with an underscore in the filter string because Rust crate names use underscores in code. The env-filter feature on tracing-subscriber is what makes that environment-variable control work.

The layer also has builder methods to change the log level, include headers, or change the latency unit, and the subscriber filter must allow whatever level the builder emits at. The setup above is the whole standard case. When the default output does not fit, the custom middleware in the sections below is usually the better next step than piling options onto this layer.

What the Default Output Looks Like

Run the server from the setup above and send a request to http://127.0.0.1:3000/. You will see three log lines in the terminal:

DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_request: started processing request
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

The first line is emitted when the request enters the layer. The second line is emitted after the response is produced. The latency field shows how long the handler took, and status shows the HTTP status code of the response. The third line is emitted when the response body stream ends, which for a small body happens almost immediately after the second line. The request{...} prefix is the span, a named context that groups all three events under one request, so the method, path, and protocol version appear on every line.

This default output is already useful. It gives you the method, path, protocol version, status code, and latency for every request without writing any logging code inside your handlers.

Three lines per request means TraceLayer works:

When each request produces a started processing request line, a finished processing request line, and an end of stream line, the layer and the subscriber are both wired correctly. When you see only some of them, or none, the subscriber filter is the first place to look.

Why You Might See Nothing at All

The most common confusion with TraceLayer is a silent terminal. You attach the layer, start the server, send requests, and nothing appears. The cause is almost always the log level.

TraceLayer sends its request and response events at DEBUG level by default. A plain tracing_subscriber::fmt().init() call sets the maximum level to INFO, which means DEBUG events are dropped before they are printed. Your handler's own info! lines still appear, but the TraceLayer lines do not, and the request{...} span context is missing from them too.

The subscriber setup above fixes this by adding tower_http=debug to the filter. That tells the subscriber to accept DEBUG events from the tower_http crate while keeping your own crate at INFO. You can also set the RUST_LOG environment variable when you run the server:

RUST_LOG=logging_demo=info,tower_http=debug cargo run

Either way, the rule is the same. The subscriber filter must allow the level the layer emits at, or the events are dropped silently. There is no error and no warning. The logs simply never appear.

TraceLayer defaults to DEBUG, not INFO:

The default level for TraceLayer request and response events is DEBUG. When your filter is set to info, you will see no request logs from tower_http unless you explicitly allow tower_http=debug in the filter or change the level with the layer's builder methods.

Writing Your Own Logging Middleware

TraceLayer is excellent for standard logging, but sometimes you need a log format that matches an existing system, or you want to calculate something specific that the default callbacks do not expose. In those cases, you can write your own middleware as an async function that brackets the handler. The function receives the incoming request and a Next value. Next represents the rest of the stack. Calling next.run(request).await passes the request forward and returns the response.

A Minimal Custom Logger

Start with the smallest possible custom logger. It prints the method and path before the handler runs, then prints the status code after:

src/main.rs
use axum::{
    extract::Request,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};

async fn log_requests(request: Request, next: Next) -> Response {
    let method = request.method().clone();
    let uri = request.uri().clone();
    println!("-> {} {}", method, uri);
    let response = next.run(request).await;
    println!("<- {} {} status {}", method, uri, response.status());
    response
}

async fn hello() -> &'static str {
    "Hello, world!"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello))
        .layer(middleware::from_fn(log_requests));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This middleware does not depend on tracing or tower-http at all. It uses println!, which is fine for learning and for small tools. When you send a request, the terminal shows the method and path on the way in, and the status code on the way out.

The important detail is that request is moved into next.run(request). You cannot use request after that line. That is why the method and URI are cloned into separate variables before the call. When you try to print request.method() after next.run, the compiler will stop you.

Measuring Latency in Custom Middleware

Latency is often the most valuable piece of information in a request log. You can measure it with std::time::Instant by taking a timestamp before next.run and calling .elapsed() after:

src/main.rs
use axum::{
    extract::Request,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};
use std::time::Instant;

async fn log_requests(request: Request, next: Next) -> Response {
    let method = request.method().clone();
    let uri = request.uri().clone();
    let start = Instant::now();
    let response = next.run(request).await;
    let latency = start.elapsed();
    let status = response.status();
    println!("{} {} -> {} in {:?}", method, uri, status, latency);
    response
}

async fn hello() -> &'static str {
    "Hello, world!"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello))
        .layer(middleware::from_fn(log_requests));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Instant::now() records the moment the middleware starts. After next.run(request).await returns, start.elapsed() gives a Duration representing the total time spent in the rest of the stack, including your handler. The log line now includes the status code and the latency. For a fast handler, the output looks like this:

GET / -> 200 OK in 245.3µs

That gives you exactly what you need to spot slow routes, the path and the time it took, in one line.

Do not consume the request body unless you rebuild it:

When you read the request body inside logging middleware, you must rebuild the request with a new body before calling next.run. The body can only be consumed once. A common beginner mistake is to collect the body for logging and then pass the original request forward. The handler then receives an empty body, and POST or PUT requests fail silently or return confusing errors. Only log the body when you have a specific need, and always reconstruct the request before passing it on.

Logging with tracing Inside Your Own Middleware

println! works, but most Axum applications use the tracing crate for structured logging. You can emit tracing events from your custom middleware just like you do from handlers.

Here is the latency logger rewritten to use tracing::info!:

src/main.rs
use axum::{
    extract::Request,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};
use std::time::Instant;
use tracing::info;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

async fn log_requests(request: Request, next: Next) -> Response {
    let method = request.method().clone();
    let uri = request.uri().clone();
    let start = Instant::now();
    let response = next.run(request).await;
    let latency = start.elapsed();
    let status = response.status();
    info!(
        method = %method,
        uri = %uri,
        status = %status,
        latency_ms = latency.as_millis() as u64,
        "request completed"
    );
    response
}

async fn hello() -> &'static str {
    "Hello, world!"
}

#[tokio::main]
async fn main() {
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "logging_demo=info".into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();
    let app = Router::new()
        .route("/", get(hello))
        .layer(middleware::from_fn(log_requests));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Using tracing::info! with named fields produces structured output. The % sigil tells tracing to record the value using its Display implementation, which is what you want for types like Method, Uri, and StatusCode. When the subscriber formats the event, it prints those fields in a machine-readable way. This is the same mechanism TraceLayer uses internally, so your custom logs and any TraceLayer logs will share a consistent format.

The subscriber filter here uses only logging_demo=info, because this middleware emits its own info! events from your crate, not from tower_http. No TraceLayer is attached in this example, so no tower_http filter entry is needed.

When to use a custom logger instead of TraceLayer:

Use TraceLayer when you want a standard, well-tested logging layer with minimal code. Use a custom async function when you need a log line that matches a specific format required by your team or your log aggregator, or when you need to compute a value that the default TraceLayer callbacks do not provide.

Choosing Between the Two Approaches

The two approaches are not rivals. They answer different needs, and many applications use both at different layers. TraceLayer gives you spans, classification of failures by status code, and callbacks for body chunks and end of stream, all without writing logging code. A custom function gives you any format and any computed value, at the cost of writing and maintaining the code yourself.

A practical rule is to start with TraceLayer. It covers the standard case, and its output is consistent across services that use it. Move to a custom function when a concrete requirement appears that TraceLayer cannot express, such as a log line format dictated by an existing system, or a value that only your application can compute. When you do move, keep the tracing events structured with named fields, so the custom logs stay as searchable as the TraceLayer ones.

Logging Only Failures

Logging every request is useful in development, but in production the interesting lines are often the failures. A custom middleware function can log only when the status code says something went wrong, and stay silent for the thousands of successful requests in between.

src/main.rs
use axum::{
    extract::Request,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};
use tracing::warn;

async fn log_failures(request: Request, next: Next) -> Response {
    let method = request.method().clone();
    let uri = request.uri().clone();
    let response = next.run(request).await;
    let status = response.status();
    if status.is_server_error() || status.is_client_error() {
        warn!(
            method = %method,
            uri = %uri,
            status = %status,
            "request failed"
        );
    }
    response
}

async fn hello() -> &'static str {
    "Hello, world!"
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();
    let app = Router::new()
        .route("/", get(hello))
        .layer(middleware::from_fn(log_failures));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to / returns 200 OK, and nothing is logged, because the status is neither a client error nor a server error. A request to an unknown path returns 404, which is a client error, so the middleware logs one warning line with the method, the path, and the status. TraceLayer can do the same job through its on_failure callback, which fires when the response is classified as a failure, but the custom version shows the mechanism plainly. Check the status after run returns, decide whether it counts as a failure, and log only then.

Where to Attach the Logging Layer

A logging layer sees only the requests that pass through it, so where you attach it decides what gets logged. Attach it to the whole router, and it logs every request, including ones that fail authentication or match no route. Attach it inside another layer, and it only sees the requests that got past the outer layer.

A logging layer placed outside an auth check logs rejected requests, which is what you usually want when you are tracking who is probing your API. A logging layer placed inside the auth check only logs requests that passed authentication, which is what you want when the log itself is sensitive and should only contain real users. There is no single right answer. The rule is to place the logging layer deliberately, and to remember that a request rejected by an outer layer never reaches a logging layer inside it.

The same thinking applies to ordering with other layers. A logging layer outside a timeout layer will record requests that timed out, because the timeout response still passes back through it. A logging layer inside a compression layer will see the response before compression, so its recorded body size, when it records one, is the uncompressed size. When a log line looks wrong, check the layer order before doubting the logger.

Common Mistakes

Forgetting to initialise the subscriber. TraceLayer and tracing::info! both emit events, but events go nowhere without a subscriber. When you see no logs, check that .init() is called on the subscriber before the server starts, and that the filter allows the level the events are emitted at.

Using the wrong Request import. The Request type in axum::http is generic over the body type, and it will cause type errors in middleware signatures. Import axum::extract::Request instead, which is pre-aliased with the correct body type.

Trying to use the request after calling next.run. The request is moved into next.run(request). Any data you need after that call, such as the method or URI, must be cloned or captured before the call.

Logging the request body without putting it back. The body is a stream that can only be read once. When your middleware reads the body and does not reconstruct the request with a new body, the handler receives an empty request body. This is especially dangerous for POST and PUT routes.

Assuming TraceLayer logs at INFO by default. The default level for TraceLayer response events is DEBUG. When your filter is set to info, you will see no request logs from tower_http unless you explicitly change the level with .on_response(DefaultOnResponse::new().level(Level::INFO)) or set the filter to tower_http=debug.

Summary

Request logging is the practice of recording what happened to every request that reaches your server. Axum gives you two ways to add it. TraceLayer from tower-http is a one-line solution that produces structured logs with method, path, status, and latency automatically, once a subscriber is installed with a filter that allows its DEBUG events. Custom middleware written as an async function gives you full control over the log format and lets you compute exactly the values you need, at the cost of writing the logging code yourself.

The most important thing to remember is that middleware is code that runs before and after your handler. Everything before next.run(request).await runs on the request. Everything after it runs on the response. Once that structure clicks, you can log anything you want, in any format you need. Start with TraceLayer for the standard case, reach for a custom function when a concrete requirement demands a different format, and always check the subscriber filter first when the terminal stays silent.