From 2600c227031f9fcebfafd0a3d83841cab62e73c1 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Tue, 21 Mar 2023 11:17:31 +0100 Subject: [PATCH] Make tracing-aka-logging example more realistic (#1869) --- examples/tracing-aka-logging/src/main.rs | 28 +++++++++++++++++++----- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/examples/tracing-aka-logging/src/main.rs b/examples/tracing-aka-logging/src/main.rs index 38093066..58ece2b5 100644 --- a/examples/tracing-aka-logging/src/main.rs +++ b/examples/tracing-aka-logging/src/main.rs @@ -6,6 +6,7 @@ use axum::{ body::Bytes, + extract::MatchedPath, http::{HeaderMap, Request}, response::{Html, Response}, routing::get, @@ -13,7 +14,7 @@ use axum::{ }; use std::{net::SocketAddr, time::Duration}; use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer}; -use tracing::Span; +use tracing::{info_span, Span}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -33,20 +34,35 @@ async fn main() { // It provides good defaults but is also very customizable. // // See https://docs.rs/tower-http/0.1.1/tower_http/trace/index.html for more details. - .layer(TraceLayer::new_for_http()) - // If you want to customize the behavior using closures here is how // - // This is just for demonstration, you don't need to add this middleware twice + // If you want to customize the behavior using closures here is how. .layer( TraceLayer::new_for_http() + .make_span_with(|request: &Request<_>| { + // Log the matched route's path (with placeholders not filled in). + // Use request.uri() or OriginalUri if you want the real path. + let matched_path = request + .extensions() + .get::() + .map(MatchedPath::as_str); + + info_span!( + "http_request", + method = ?request.method(), + matched_path, + some_other_field = tracing::field::Empty, + ) + }) .on_request(|_request: &Request<_>, _span: &Span| { - // ... + // You can use `_span.record("some_other_field", value)` in one of these + // closures to attach a value to the initially empty field in the info_span + // created above. }) .on_response(|_response: &Response, _latency: Duration, _span: &Span| { // ... }) .on_body_chunk(|_chunk: &Bytes, _latency: Duration, _span: &Span| { - // .. + // ... }) .on_eos( |_trailers: Option<&HeaderMap>, _stream_duration: Duration, _span: &Span| {