mirror of
https://github.com/tokio-rs/axum.git
synced 2025-03-13 19:27:53 +01:00
Make tracing-aka-logging example more realistic (#1869)
This commit is contained in:
parent
03e8bc77f1
commit
2600c22703
1 changed files with 22 additions and 6 deletions
|
@ -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::<MatchedPath>()
|
||||
.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| {
|
||||
|
|
Loading…
Add table
Reference in a new issue