Skip to main content

obsidian_cli_inspector/
logger.rs

1use anyhow::Result;
2use std::fs::{self, OpenOptions};
3use std::io::Write;
4use std::path::PathBuf;
5
6pub struct Logger {
7    log_path: PathBuf,
8}
9
10impl Logger {
11    pub fn new(log_dir: PathBuf) -> Result<Self> {
12        fs::create_dir_all(&log_dir)?;
13
14        Ok(Logger { log_path: log_dir })
15    }
16
17    pub fn get_log_file(&self, command: &str) -> PathBuf {
18        let timestamp = chrono::Local::now().format("%Y%m%d_%H%M%S");
19        self.log_path.join(format!("{command}_{timestamp}.log"))
20    }
21
22    pub fn log(&self, command: &str, message: &str) -> Result<()> {
23        let log_file = self.get_log_file(command);
24        let mut file = OpenOptions::new()
25            .create(true)
26            .append(true)
27            .open(&log_file)?;
28
29        let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
30        writeln!(file, "[{timestamp}] {message}")?;
31
32        Ok(())
33    }
34
35    pub fn log_section(&self, command: &str, title: &str) -> Result<()> {
36        let log_file = self.get_log_file(command);
37        let mut file = OpenOptions::new()
38            .create(true)
39            .append(true)
40            .open(&log_file)?;
41
42        let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
43        writeln!(file, "\n[{timestamp}] === {title} ===")?;
44
45        Ok(())
46    }
47
48    pub fn print_and_log(&self, command: &str, message: &str) -> Result<()> {
49        println!("{message}");
50        self.log(command, message)?;
51        Ok(())
52    }
53}