use std::fs::{self, File};
use std::io::Write;
use std::path::PathBuf;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
pub struct MonLog {
pub enabled: bool,
pub interval: Duration,
pub retention_days: u32,
last: Instant,
file: Option<(PathBuf, File)>,
host: String,
}
impl MonLog {
pub fn new(interval: Duration, retention_days: u32, host: String) -> Self {
Self {
enabled: false,
interval,
retention_days,
last: Instant::now(),
file: None,
host,
}
}
pub fn purge_old(&self) -> usize {
if self.retention_days == 0 {
return 0;
}
let cutoff = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
.saturating_sub(self.retention_days as u64 * 86_400);
let dir = log_dir();
let Ok(rd) = fs::read_dir(&dir) else {
return 0;
};
let mut removed = 0;
for e in rd.flatten() {
let path = e.path();
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
let Some(ts) = session_ts(name) else {
continue;
};
if ts < cutoff && fs::remove_file(&path).is_ok() {
removed += 1;
}
}
removed
}
pub fn toggle(&mut self) -> Option<PathBuf> {
if self.enabled {
self.finalize();
return None;
}
let dir = log_dir();
if fs::create_dir_all(&dir).is_err() {
return None;
}
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let path = dir.join(format!("ltop-log-{secs}-{}.jsonl", std::process::id()));
let Ok(f) = File::create(&path) else {
return None;
};
let mut file = (path.clone(), f);
let host = json_str(&self.host);
let iv = self.interval.as_secs();
let _ = writeln!(
file.1,
"{{\"session_start\":{secs},\"host\":\"{host}\",\"interval_s\":{iv}}}"
);
self.file = Some(file);
self.enabled = true;
self.last = Instant::now();
let _ = self.purge_old();
Some(path)
}
pub fn maybe_write(&mut self, snap: &crate::snapshot::Snapshot) {
if !self.enabled || self.last.elapsed() < self.interval {
return;
}
self.last = Instant::now();
self.write_snapshot_v2(snap);
}
pub fn finalize(&mut self) {
if let Some((path, mut f)) = self.file.take() {
let _ = f.flush();
eprintln!(
"{}",
crate::pick_s(
crate::cli_lang_zh(),
&format!("ltop: monitoring log saved to {}", path.display()),
&format!("ltop: 监控日志已保存到 {}", path.display())
)
);
}
self.enabled = false;
}
fn write_snapshot_v2(&mut self, snap: &crate::snapshot::Snapshot) {
let Some((_, f)) = self.file.as_mut() else {
return;
};
let _ = writeln!(f, "{}", serde_json::to_string(snap).unwrap_or_default());
}
}
pub(crate) fn log_dir() -> PathBuf {
if let Ok(x) = std::env::var("XDG_STATE_HOME") {
if !x.is_empty() {
return PathBuf::from(x).join("ltop");
}
}
match std::env::var("HOME") {
Ok(h) if !h.is_empty() => PathBuf::from(h).join(".local/state/ltop"),
_ => PathBuf::from("/tmp/ltop"),
}
}
fn session_ts(name: &str) -> Option<u64> {
parse_prefixed_ts(name, &["ltop-log-", "session-"])
}
pub(crate) fn session_file_ts(name: &str) -> Option<u64> {
parse_prefixed_ts(name, &["ltop-log-", "ltop-session-", "session-"])
}
fn parse_prefixed_ts(name: &str, prefixes: &[&str]) -> Option<u64> {
let stem = prefixes
.iter()
.find_map(|p| name.strip_prefix(p))?
.strip_suffix(".jsonl")?;
stem.split('-').next()?.parse::<u64>().ok()
}
pub(crate) fn json_str(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_session_file_names() {
assert_eq!(session_ts("session-1792368483.jsonl"), Some(1792368483));
assert_eq!(session_ts("ltop-log-1792368483.jsonl"), Some(1792368483));
assert_eq!(session_ts("ltop-log-1792368483-1234.jsonl"), Some(1792368483));
assert_eq!(session_ts("session-abc.jsonl"), None);
assert_eq!(session_ts("other.jsonl"), None);
assert_eq!(session_ts("session-12.txt"), None);
assert_eq!(session_ts("ltop-session-1792368483.jsonl"), None);
assert_eq!(
session_file_ts("ltop-session-1792368483-99.jsonl"),
Some(1792368483)
);
assert_eq!(session_file_ts("ltop-log-1792368483.jsonl"), Some(1792368483));
assert_eq!(session_file_ts("session-1792368483.jsonl"), Some(1792368483));
assert_eq!(session_file_ts("other.jsonl"), None);
}
}