Skip to content

Instantly share code, notes, and snippets.

@DefectingCat
Created December 12, 2023 03:09
Show Gist options
  • Save DefectingCat/e2dcde5afb548233db0ed85106ba6bbc to your computer and use it in GitHub Desktop.
Save DefectingCat/e2dcde5afb548233db0ed85106ba6bbc to your computer and use it in GitHub Desktop.
Trace layer for axum
use tower_http::trace::{
DefaultMakeSpan, DefaultOnBodyChunk, DefaultOnEos, DefaultOnFailure, DefaultOnRequest,
DefaultOnResponse, TraceLayer,
};
use tracing::Level;
/// Constructs a TraceLayer for Axum applications to enable logging and tracing of HTTP requests and responses.
///
/// The TraceLayer is a middleware layer that integrates with Tower HTTP's tracing capabilities.
/// It provides detailed information about the execution of HTTP requests and responses, allowing for
/// effective monitoring and debugging.
///
/// # Example
///
/// ```rust
/// Router::new()
/// .route("/", get(hello).post(hello))
/// .layer(tracing_layer())
/// }
/// ```
///
/// The provided function configures various aspects of tracing, such as the log level for different events.
/// By default, it sets the log level for request, response, and end-of-stream (EOS) events to INFO.
/// It uses the `ServerErrorsAsFailures` classifier, treating server errors as failures for tracing purposes.
///
/// # Returns
///
/// A `TraceLayer` configured with default settings for HTTP tracing in Axum applications.
pub fn tracing_layer() -> tower_http::trace::TraceLayer<
tower_http::classify::SharedClassifier<tower_http::classify::ServerErrorsAsFailures>,
> {
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::default().level(Level::INFO))
.on_request(DefaultOnRequest::default().level(Level::INFO))
.on_response(DefaultOnResponse::default().level(Level::INFO))
.on_body_chunk(DefaultOnBodyChunk::default())
.on_eos(DefaultOnEos::default().level(Level::INFO))
.on_failure(DefaultOnFailure::default().level(Level::INFO))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment