Files
axum/examples/tracing-aka-logging/src/main.rs
T
David PedersenandGitHub 1fe4558362 Move examples to separate workspace (#978)
* Move examples to separate workspace

* update commands to run examples

* remove debug
2022-04-29 18:53:41 +02:00

75 lines
2.4 KiB
Rust

//! Run with
//!
//! ```not_rust
//! cd examples && cargo run -p example-tracing-aka-logging
//! ```
use axum::{
body::Bytes,
http::{HeaderMap, Request},
response::{Html, Response},
routing::get,
Router,
};
use std::{net::SocketAddr, time::Duration};
use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer};
use tracing::Span;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG")
.unwrap_or_else(|_| "example_tracing_aka_logging=debug,tower_http=debug".into()),
))
.with(tracing_subscriber::fmt::layer())
.init();
// build our application with a route
let app = Router::new()
.route("/", get(handler))
// `TraceLayer` is provided by tower-http so you have to add that as a dependency.
// 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
.layer(
TraceLayer::new_for_http()
.on_request(|_request: &Request<_>, _span: &Span| {
// ...
})
.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| {
// ...
},
)
.on_failure(
|_error: ServerErrorsFailureClass, _latency: Duration, _span: &Span| {
// ...
},
),
);
// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}