tdm_server_rust/middleware/
error_log.rs1use crate::{middleware::AuthMember, utils::error_log};
16use axum::{body::Body, http::Request, middleware::Next, response::Response};
17use bytes::Bytes;
18use http_body_util::BodyExt;
19
20#[tracing::instrument(skip_all, level = "info")]
22pub async fn error_log_middleware(req: Request<Body>, next: Next) -> Response {
23 let method = req.method().to_string();
24 let path = api_request_path(req.uri().path());
25 let member_id = req
26 .extensions()
27 .get::<AuthMember>()
28 .and_then(|auth| auth.0.as_ref().map(|m| m.id));
29
30 let response = next.run(req).await;
31 let status = response.status().as_u16();
32
33 if status < 400 {
34 return response;
35 }
36
37 let (parts, body) = response.into_parts();
38 let body_bytes: Bytes = body
39 .collect()
40 .await
41 .map(|b| b.to_bytes())
42 .unwrap_or_default();
43 let body_str = String::from_utf8_lossy(&body_bytes);
44 error_log::log_http_error(&method, &path, status, &body_str, member_id);
45
46 Response::from_parts(parts, Body::from(body_bytes))
47}
48
49fn api_request_path(path: &str) -> String {
54 if path.starts_with("/api/") || path == "/api" {
55 path.to_string()
56 } else {
57 format!("/api{path}")
58 }
59}