libobs_wrapper\logger/
file.rs

1use std::{fs::File, path::Path};
2
3use chrono::Local;
4
5use super::ObsLogger;
6use crate::utils::ObsError;
7
8/// A logger that writes logs to a file
9#[derive(Debug)]
10pub struct FileLogger {
11    file: File,
12}
13
14impl FileLogger {
15    /// Creates a new `FileLogger`, which writes to a log file formatted by the current time.
16    /// This does not implement any rotary logging or similar, so there'll be a log file for every time your ObsContext is being started up.
17    pub fn from_dir(dir: &Path) -> Result<Self, ObsError> {
18        let current_local = Local::now();
19        let custom_format = current_local.format("%Y-%m-%d-%H-%M-%S");
20
21        Ok(Self {
22            file: File::create(dir.join(format!("obs-{}.log", custom_format)))
23                .map_err(|e| ObsError::IoError(e.to_string()))?,
24        })
25    }
26
27    /// Creates a new `FileLogger` which will pipe the libobs output directly to the file given.
28    pub fn from_file(file: &Path) -> Result<Self, ObsError> {
29        Ok(Self {
30            file: File::create(file).map_err(|e| ObsError::IoError(e.to_string()))?,
31        })
32    }
33}
34
35impl ObsLogger for FileLogger {
36    fn log(&mut self, level: crate::enums::ObsLogLevel, msg: String) {
37        use std::io::Write;
38        writeln!(self.file, "[{:?}] {}", level, msg).unwrap();
39    }
40}