main.rs
This file
Path
examples/request-id/src/main.rs
64 lines · 2.1 KiB · Rust
Last changed by
examples: Refactor request-id example (#3865)tottotobefore adoption97def95
History of this fileTake it
1//! Run with2//!3//! ```not_rust4//! cargo run -p example-request-id5//! ```67use axum::{http::Request, response::Html, routing::get, Router};8use tower::ServiceBuilder;9use tower_http::{10 request_id::{MakeRequestUuid, RequestId},11 trace::TraceLayer,12 ServiceBuilderExt,13};14use tracing::{info, info_span};15use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};1617#[tokio::main]18async fn main() {19 tracing_subscriber::registry()20 .with(21 tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {22 // axum logs rejections from built-in extractors with the `axum::rejection`23 // target, at `TRACE` level. `axum::rejection=trace` enables showing those events24 format!(25 "{}=debug,tower_http=debug,axum::rejection=trace",26 env!("CARGO_CRATE_NAME")27 )28 .into()29 }),30 )31 .with(tracing_subscriber::fmt::layer())32 .init();3334 let middleware = ServiceBuilder::new()35 .set_x_request_id(MakeRequestUuid)36 .layer(37 TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {38 // Log the request id as generated.39 let request_id = request.extensions().get::<RequestId>().unwrap();4041 match request_id.header_value().to_str() {42 Ok(request_id) => info_span!("http_request", request_id),43 Err(_) => info_span!("http_request", request_id = ?request_id),44 }45 }),46 )47 // send headers from request to response headers48 .propagate_x_request_id();4950 // build our application with a route51 let app = Router::new().route("/", get(handler)).layer(middleware);5253 // run it54 let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")55 .await56 .unwrap();57 println!("listening on {}", listener.local_addr().unwrap());58 axum::serve(listener, app).await;59}6061async fn handler() -> Html<&'static str> {62 info!("Hello world!");63 Html("<h1>Hello, World!</h1>")64}