Files
rust-work/redis-proxy/src/logger.rs
T
lxy 95dfe8504d 优化: ssh/mongo/redis-proxy 超时分级与日志默认开
- ssh: exec_timeout_secs 600s(408断会话)/idle 300→1800s/日志级别规则/截断500→2000
- mongo/redis: query_timeout 60s + idle_timeout 落配置
- 四代理: 日志默认开启(default_log_path exe同目录logs/),未设env也记录
- mysql: default_log_path 共享实现注释同步
2026-10-28 22:56:02 +08:00

93 lines
3.4 KiB
Rust

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<Option<File>>,
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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub command: Option<String>,
#[serde(rename = "durationMs")]
pub duration_ms: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
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::<String>()) }
}
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) }
}