use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Mutex;
use crate::args::Level;
use crate::util;
pub struct Logger {
level: Level,
file: Mutex<Option<File>>,
path: PathBuf,
}
impl Logger {
#[must_use]
pub fn init(level: Level) -> Self {
let (y, m, d) = util::today_utc();
let dir = crate::args::data_dir().join("logs");
let path = dir.join(format!("ek-server-{y:04}{m:02}{d:02}.log"));
let file = if fs::create_dir_all(&dir).is_ok() {
OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.ok()
} else {
None
};
Self {
level,
file: Mutex::new(file),
path,
}
}
#[must_use]
pub fn path(&self) -> &PathBuf {
&self.path
}
pub fn error(&self, msg: &str) {
self.write(Level::Error, msg);
}
pub fn warn(&self, msg: &str) {
self.write(Level::Warn, msg);
}
pub fn info(&self, msg: &str) {
self.write(Level::Info, msg);
}
pub fn debug(&self, msg: &str) {
self.write(Level::Debug, msg);
}
fn write(&self, lvl: Level, msg: &str) {
if lvl > self.level {
return;
}
let line = format!(
"[{} {:?}] {}",
util::unix_secs(),
lvl,
msg
);
eprintln!("{line}");
if let Ok(mut guard) = self.file.lock()
&& let Some(f) = guard.as_mut()
{
let _ = writeln!(f, "{line}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn logger_creates_file_and_respects_level() {
let dir = std::env::temp_dir().join(format!("ek-api-log-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("test.log");
let f = OpenOptions::new().create(true).append(true).open(&path).unwrap();
let lg = Logger {
level: Level::Warn,
file: Mutex::new(Some(f)),
path: path.clone(),
};
lg.info("info-should-be-dropped");
lg.warn("warn-should-land");
let text = std::fs::read_to_string(&path).unwrap();
assert!(!text.contains("info-should-be-dropped"));
assert!(text.contains("warn-should-land"));
std::fs::remove_dir_all(&dir).ok();
}
}