examples: Refactor request-id example (#3865)

This commit is contained in:
tottoto
2026-08-15 10:40:51 +02:00
committed by GitHub
parent 6ab6f99aac
commit 97def9590a
2 changed files with 11 additions and 28 deletions
+1 -1
View File
@@ -8,6 +8,6 @@ publish = false
axum = { path = "../../axum" }
tokio = { version = "1.0", features = ["full"] }
tower = "0.5.2"
tower-http = { version = "0.6", features = ["request-id", "trace"] }
tower-http = { version = "0.6", features = ["request-id", "trace", "util"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+10 -27
View File
@@ -4,22 +4,16 @@
//! cargo run -p example-request-id
//! ```
use axum::{
http::{HeaderName, Request},
response::Html,
routing::get,
Router,
};
use axum::{http::Request, response::Html, routing::get, Router};
use tower::ServiceBuilder;
use tower_http::{
request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer},
request_id::{MakeRequestUuid, RequestId},
trace::TraceLayer,
ServiceBuilderExt,
};
use tracing::{error, info, info_span};
use tracing::{info, info_span};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
const REQUEST_ID_HEADER: &str = "x-request-id";
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
@@ -37,32 +31,21 @@ async fn main() {
.with(tracing_subscriber::fmt::layer())
.init();
let x_request_id = HeaderName::from_static(REQUEST_ID_HEADER);
let middleware = ServiceBuilder::new()
.layer(SetRequestIdLayer::new(
x_request_id.clone(),
MakeRequestUuid,
))
.set_x_request_id(MakeRequestUuid)
.layer(
TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
// Log the request id as generated.
let request_id = request.headers().get(REQUEST_ID_HEADER);
let request_id = request.extensions().get::<RequestId>().unwrap();
match request_id {
Some(request_id) => info_span!(
"http_request",
request_id = ?request_id,
),
None => {
error!("could not extract request_id");
info_span!("http_request")
}
match request_id.header_value().to_str() {
Ok(request_id) => info_span!("http_request", request_id),
Err(_) => info_span!("http_request", request_id = ?request_id),
}
}),
)
// send headers from request to response headers
.layer(PropagateRequestIdLayer::new(x_request_id));
.propagate_x_request_id();
// build our application with a route
let app = Router::new().route("/", get(handler)).layer(middleware);