Skip to content

Commit

Permalink
feat: [#468] add custom request log
Browse files Browse the repository at this point in the history
```
2024-02-12T18:24:13.404193511+00:00 [API][INFO] request; method=GET uri=/v1/about/license request_id=a5030c7a-5302-49d4-8e66-f0f0ab0e3ce3
2024-02-12T18:24:13.404380120+00:00 [API][INFO] response; latency=0 status=200 OK request_id=a5030c7a-5302-49d4-8e66-f0f0ab0e3ce3
```

Add

- request id
- uri
- method
  • Loading branch information
josecelano committed Feb 12, 2024
1 parent 91f818e commit a206737
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/web/api/server/v1/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use tower_http::compression::CompressionLayer;
use tower_http::cors::CorsLayer;
use tower_http::propagate_header::PropagateHeaderLayer;
use tower_http::request_id::{MakeRequestId, RequestId, SetRequestIdLayer};
use tower_http::trace::{DefaultMakeSpan, DefaultOnRequest, TraceLayer};
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
use tracing::{Level, Span};
use uuid::Uuid;

Expand Down Expand Up @@ -62,7 +62,19 @@ pub fn router(app_data: Arc<AppData>) -> Router {
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
.on_request(DefaultOnRequest::new().level(Level::INFO))
.on_request(|request: &Request<axum::body::Body>, _span: &Span| {
let method = request.method().to_string();
let uri = request.uri().to_string();
let request_id = request
.headers()
.get("x-request-id")
.map(|v| v.to_str().unwrap_or_default())
.unwrap_or_default();

tracing::span!(
target: "API",
tracing::Level::INFO, "request", method = %method, uri = %uri, request_id = %request_id);
})
.on_response(|response: &Response, latency: Duration, _span: &Span| {
let status_code = response.status();
let request_id = response
Expand All @@ -74,7 +86,7 @@ pub fn router(app_data: Arc<AppData>) -> Router {

tracing::span!(
target: "API",
tracing::Level::INFO, "finished processing request", latency = %latency_ms, status = %status_code, request_id = %request_id);
tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id);
}),
)
}
Expand Down

0 comments on commit a206737

Please sign in to comment.