dogy_backend_api/middleware/log/
core.rs

1use crate::{
2    error::{ClientError, Error, Result},
3    middleware::auth::layer::CurrentUser,
4};
5use axum::http::Uri;
6use reqwest::Method;
7use serde::Serialize;
8use serde_json::Value;
9use tracing::{error, info};
10use uuid::Uuid;
11
12#[derive(Debug, Serialize)]
13pub struct ClientErrorResponse {
14    pub status: String,
15    pub code: Option<Value>,
16    #[serde(skip_serializing_if = "Option::is_none")]
17    pub details: Option<Value>,
18}
19
20pub fn log_request(
21    current_user: Option<&CurrentUser>,
22    req_path: Uri,
23    req_method: Method,
24    web_error: Option<&Error>,
25    client_error: Option<ClientError>,
26) -> Result<()> {
27    let req_id = Uuid::now_v7();
28    let req_path_str = req_path.to_string();
29    let user_id = if let Some(user) = current_user {
30        user.user_id.clone()
31    } else {
32        "None".to_string()
33    };
34
35    let error_details = serde_json::to_value(web_error)
36        .ok()
37        .and_then(|mut v| v.get_mut("details").map(|v| v.take()));
38
39    if web_error.is_some() {
40        error!(
41            id = %req_id,
42            user_id = %user_id,
43            path = %req_path_str,
44            method = %req_method.as_str(),
45            client_error = %client_error.map(|e| e.as_ref().to_string()).unwrap(),
46            server_error = %web_error.map(|e| e.to_string()).unwrap(),
47            "{error_details:?}"
48        );
49    } else {
50        info!(
51            id = %req_id,
52            user_id = %user_id,
53            path = %req_path_str,
54            method = %req_method.as_str()
55        );
56    };
57
58    Ok(())
59}