use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use chrono::Local;
fn log_path_cell() -> &'static PathBuf {
static LOG_PATH: OnceLock<PathBuf> = OnceLock::new();
LOG_PATH.get_or_init(|| std::env::temp_dir().join("peter-commander.log"))
}
pub fn log_error(message: &str) {
log_to(log_path_cell(), message);
}
pub fn log_info(message: &str) {
log_to(log_path_cell(), message);
}
pub fn log_path() -> &'static Path {
log_path_cell()
}
fn log_to(path: &Path, message: &str) {
if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) {
let _ = writeln!(
file,
"[{}] {}",
Local::now().format("%Y-%m-%d %H:%M:%S"),
message
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn writes_a_line_to_the_log() {
let path = std::env::temp_dir().join("pc_test_logging.log");
let _ = std::fs::remove_file(&path);
log_to(&path, "test message");
let contents = std::fs::read_to_string(&path).unwrap();
assert!(contents.contains("test message"));
std::fs::remove_file(&path).unwrap();
}
}