FAQ - Help and questions

How do I log requests in axum with tracing and tower-http?

#axum#logging#tracing#tower-httppublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Install a tracing-subscriber formatter with an EnvFilter at start-up, add tower-http TraceLayer to the router, and write your own events with tracing::info!. RUST_LOG then controls what is shown, with no rebuild: set it to a level, or to a level per module such as tower_http=debug.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, Windows 11; tracing 0.1.44, tracing-subscriber 0.3.23, tower-http 0.6.11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

tracing records events and spans; tracing-subscriber decides what to print; TraceLayer creates one span per request and events when it starts and finishes.

src/main.rsrust
use axum::{body::Body, http::Request, routing::get, Router};
use tower::ServiceExt;
use tower_http::trace::TraceLayer;
use tracing_subscriber::EnvFilter;

async fn hello() -> &'static str {
    tracing::info!("inside the handler");
    "hi"
}

#[tokio::main]
async fn main() {
    // RUST_LOG wins when it is set; otherwise: info for everything, debug for tower_http.
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info,tower_http=debug"));
    tracing_subscriber::fmt().with_env_filter(filter).without_time().with_ansi(false).init();

    let app = Router::new().route("/hello", get(hello)).layer(TraceLayer::new_for_http());
    for uri in ["/hello", "/missing"] {
        let _ = app.clone().oneshot(Request::get(uri).body(Body::empty()).unwrap()).await.unwrap();
    }
}

Output (time stamps were turned off with without_time() so the lines are stable; the latency printed by your machine may differ):

text
DEBUG request{method=GET uri=/hello version=HTTP/1.1}: tower_http::trace::on_request: started processing request
 INFO request{method=GET uri=/hello version=HTTP/1.1}: t41: inside the handler
DEBUG request{method=GET uri=/hello version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
DEBUG request{method=GET uri=/missing version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=GET uri=/missing version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=404
  • The request{method=GET uri=/hello ...}: prefix is the request span. The handler's own info! line is printed inside it, so you can tell which request it belongs to.
  • tower_http::trace::on_response reports the status and the time taken.
  • The /missing request has status 404, so unknown paths show up too.

Changing RUST_LOG changes the output without rebuilding (all runs of the same program):

RUST_LOGResult
not setthe default in the code: info for everything, debug for tower_http (output above)
warnnothing was printed, because no warning happened
t41=infoonly INFO t41: inside the handler
Cargo.tomltoml
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
tower-http = { version = "0.6.11", features = ["trace"] }

Common mistakes#

  • Logging request bodies, headers such as Authorization, or cookies. They contain secrets (see the thread on keeping secrets out of logs).
  • Calling .init() twice. A second global subscriber is an error; set it up once in main.
  • Using println! for server logs: no levels, no filtering, no request context.

Can the logs be JSON for a log collector?#

tracing-subscriber has a JSON formatter behind a feature flag; this thread did not compile it.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet