simple_logger_rs/logging/
logger.rs

1use crate::logging::log_entry::LogEntry;
2use std::fs::{File, OpenOptions};
3use std::io::Write;
4use std::path::{Path, PathBuf};
5use std::sync::Mutex;
6use std::{fs, io};
7
8pub struct Logger {
9    log_path: Mutex<PathBuf>,
10}
11
12impl Logger {
13    pub fn new(log_path: PathBuf) -> Result<Self, io::Error> {
14        if !log_path.exists() {
15            fs::create_dir_all(log_path.parent().unwrap())?;
16        }
17
18        Ok(Self {
19            log_path: Mutex::new(log_path),
20        })
21    }
22
23    pub fn get_log_file_path(&self) -> PathBuf {
24        self.log_path.lock().unwrap().clone()
25    }
26
27    fn get_log_file(path: &Path) -> io::Result<File> {
28        OpenOptions::new().create(true).append(true).open(path)
29    }
30
31    pub fn log(&self, log_entry: &LogEntry) -> io::Result<usize> {
32        let path = self.log_path.lock().unwrap();
33        match Self::get_log_file(path.as_path()) {
34            Ok(mut log_file) => log_file.write(log_entry.to_string().as_bytes()),
35            Err(err) => Err(err),
36        }
37    }
38}