feat: JSON-Logging mit Correlation-ID, Anfrage-Log und Audit (M2.4)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -4,6 +4,7 @@ use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
@ -63,6 +64,43 @@ pub(crate) fn log_tail(path: &Path, max_lines: usize) -> String {
|
||||
lines[from..].join("\n")
|
||||
}
|
||||
|
||||
/// Hebt eine vorhandene Logdatei auf (`<name>.<unix-sekunden>`) und löscht die
|
||||
/// ältesten aufgehobenen Logs im selben Ordner, sodass höchstens `keep`
|
||||
/// bleiben. Nur Dateien nach dem Muster `instance-*.log.*` werden angefasst.
|
||||
pub(crate) fn rotate_log(path: &Path, keep: usize) -> std::io::Result<()> {
|
||||
if path.exists() {
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
let base = path.display().to_string();
|
||||
let mut target = format!("{base}.{secs}");
|
||||
let mut n = 1;
|
||||
while Path::new(&target).exists() {
|
||||
target = format!("{base}.{secs}-{n}");
|
||||
n += 1;
|
||||
}
|
||||
std::fs::rename(path, target)?;
|
||||
}
|
||||
let Some(dir) = path.parent() else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut old: Vec<(SystemTime, std::path::PathBuf)> = std::fs::read_dir(dir)?
|
||||
.flatten()
|
||||
.filter(|e| {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
name.starts_with("instance-") && name.contains(".log.")
|
||||
})
|
||||
.filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
|
||||
.collect();
|
||||
old.sort();
|
||||
let surplus = old.len().saturating_sub(keep);
|
||||
for (_, file) in old.into_iter().take(surplus) {
|
||||
let _ = std::fs::remove_file(file);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verwaltet die Ports eines Bereichs: ein Port gilt als belegt, wenn wir ihn
|
||||
/// vergeben haben oder auf `127.0.0.1` schon jemand lauscht.
|
||||
pub(crate) struct PortPool {
|
||||
@ -129,6 +167,47 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_hebt_die_alte_datei_auf_und_behaelt_nur_die_neuesten() {
|
||||
let dir = std::env::temp_dir().join(format!("nexus-adapter-rotate-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let current = dir.join("instance-1.log");
|
||||
std::fs::write(dir.join("fremd.log.1"), "bleibt").unwrap();
|
||||
|
||||
// Nichts zu rotieren.
|
||||
rotate_log(¤t, 2).unwrap();
|
||||
assert!(!current.exists());
|
||||
|
||||
for n in 0..4 {
|
||||
std::fs::write(¤t, format!("lauf {n}")).unwrap();
|
||||
rotate_log(¤t, 2).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert!(!current.exists(), "die aktuelle Datei wurde aufgehoben");
|
||||
let mut rotated: Vec<String> = std::fs::read_dir(&dir)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.starts_with("instance-1.log."))
|
||||
.collect();
|
||||
rotated.sort();
|
||||
assert_eq!(rotated.len(), 2, "{rotated:?}");
|
||||
let inhalte: Vec<String> = rotated
|
||||
.iter()
|
||||
.map(|n| std::fs::read_to_string(dir.join(n)).unwrap())
|
||||
.collect();
|
||||
assert!(
|
||||
inhalte.contains(&"lauf 3".to_string()) && inhalte.contains(&"lauf 2".to_string()),
|
||||
"{inhalte:?}"
|
||||
);
|
||||
assert!(
|
||||
dir.join("fremd.log.1").exists(),
|
||||
"fremde Dateien bleiben unberührt"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portpool_vergibt_jeden_port_nur_einmal_und_gibt_frei() {
|
||||
// Ein Bereich mit einem einzigen Port.
|
||||
|
||||
Reference in New Issue
Block a user