use serde::{Deserialize, Serialize}; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::PathBuf; use std::sync::Mutex; pub struct RequestLogger { log_file: Mutex>, enabled: bool, } impl RequestLogger { pub fn new(log_path: Option<&str>) -> Self { let (log_file, enabled) = if let Some(path) = log_path { let path = expand_path(path); if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); } match OpenOptions::new().create(true).append(true).open(&path) { Ok(file) => (Some(file), true), Err(e) => { eprintln!("[Logger] Failed to open log file {}: {}", path.display(), e); (None, false) } } } else { (None, false) }; Self { log_file: Mutex::new(log_file), enabled } } pub fn is_enabled(&self) -> bool { self.enabled } pub fn log(&self, entry: &LogEntry) { if !self.enabled { return; } let json = match serde_json::to_string(entry) { Ok(j) => j, Err(e) => { eprintln!("[Logger] Failed to serialize log: {}", e); return; } }; if let Ok(mut file) = self.log_file.lock() { if let Some(ref mut f) = *file { let _ = writeln!(f, "{}", json); } } } } #[derive(Debug, Serialize, Deserialize)] pub struct LogEntry { pub timestamp: String, pub level: String, #[serde(rename = "type")] pub log_type: String, pub client: String, pub endpoint: String, #[serde(skip_serializing_if = "Option::is_none")] pub conn: Option, #[serde(skip_serializing_if = "Option::is_none")] pub command: Option, #[serde(rename = "durationMs")] pub duration_ms: u64, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option, } impl LogEntry { pub fn new(endpoint: &str, client: &str) -> Self { Self { timestamp: current_timestamp(), level: "INFO".to_string(), log_type: "request".to_string(), client: client.to_string(), endpoint: endpoint.to_string(), conn: None, command: None, duration_ms: 0, error: None, } } pub fn with_conn(mut self, conn: &str) -> Self { self.conn = Some(conn.to_string()); self } pub fn with_command(mut self, cmd: &str) -> Self { self.command = Some(truncate_string(cmd, 2000)); self } pub fn with_duration(mut self, ms: u64) -> Self { self.duration_ms = ms; if ms > 5000 && self.level == "INFO" { self.level = "ERROR".to_string(); } else if ms > 2000 && self.level == "INFO" { self.level = "WARN".to_string(); } self } pub fn with_error(mut self, error: &str) -> Self { self.level = "ERROR".to_string(); self.error = Some(error.to_string()); self } } fn current_timestamp() -> String { time::OffsetDateTime::now_utc() .format(&time::macros::format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]")) .unwrap_or_default() } fn truncate_string(s: &str, max_len: usize) -> String { if s.chars().count() <= max_len { s.to_string() } else { format!("{}... (truncated)", s.chars().take(max_len).collect::()) } } fn expand_path(path: &str) -> PathBuf { if path.starts_with('~') { let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default(); PathBuf::from(path.replacen('~', &home, 1)) } else { PathBuf::from(path) } }