fil_logger/
single_file_writer.rs

1use std::fs::File;
2use std::io::Write;
3use std::sync::Mutex;
4
5use log::Record;
6
7use flexi_logger::writers::LogWriter;
8use flexi_logger::{default_format, DeferredNow, FormatFunction};
9
10/// A `LogWriter` that accepts an open `File`
11pub struct SingleFileWriter {
12    // The state needs to be mutable; since `Log.log()` requires an unmutable self,
13    // which translates into a non-mutating `LogWriter::write()`,
14    // we need internal mutability and thread-safety.
15    state: Mutex<File>,
16    // The format function to use
17    format: FormatFunction,
18}
19
20impl SingleFileWriter {
21    /// Create a a new instance that logs into the given file.
22    pub fn new(file: File) -> Self {
23        Self {
24            state: Mutex::new(file),
25            format: default_format,
26        }
27    }
28}
29
30impl LogWriter for SingleFileWriter {
31    #[inline]
32    fn write(&self, now: &mut DeferredNow, record: &Record) -> std::io::Result<()> {
33        let mut file = self.state.lock().unwrap();
34        (self.format)(&mut *file, now, record)?;
35        // Add a newline as the line formatters don't add one
36        writeln!(&mut file)
37    }
38
39    #[inline]
40    fn flush(&self) -> std::io::Result<()> {
41        let mut file = self.state.lock().unwrap();
42        file.flush()
43    }
44
45    fn format(&mut self, format: FormatFunction) {
46        self.format = format;
47    }
48
49    #[inline]
50    fn max_log_level(&self) -> log::LevelFilter {
51        log::LevelFilter::Trace
52    }
53}