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