]> git.proxmox.com Git - pve-installer.git/blame - proxmox-auto-installer/src/log.rs
cargo clippy --fix
[pve-installer.git] / proxmox-auto-installer / src / log.rs
CommitLineData
c7edc2e1
AL
1use anyhow::{bail, Result};
2use log::{Level, Metadata, Record};
3use std::{fs::File, io::Write, sync::Mutex, sync::OnceLock};
4
5pub struct AutoInstLogger;
6static LOGFILE: OnceLock<Mutex<File>> = OnceLock::new();
7
8impl AutoInstLogger {
9 pub fn init(path: &str) -> Result<()> {
10 let f = File::create(path)?;
11 if LOGFILE.set(Mutex::new(f)).is_err() {
12 bail!("Cannot set LOGFILE")
13 }
14 Ok(())
15 }
16}
17
18impl log::Log for AutoInstLogger {
19 fn enabled(&self, metadata: &Metadata) -> bool {
20 metadata.level() <= Level::Info
21 }
22
34a12583 23 /// Logs to both, stderr and into a log file
c7edc2e1
AL
24 fn log(&self, record: &Record) {
25 if self.enabled(record.metadata()) {
34a12583 26 eprintln!("{}: {}", record.level(), record.args());
c7edc2e1
AL
27 let mut file = LOGFILE
28 .get()
29 .expect("could not get LOGFILE")
30 .lock()
31 .expect("could not get mutex for LOGFILE");
810c860d 32 writeln!(file, "{}: {}", record.level(), record.args())
c7edc2e1
AL
33 .expect("could not write to LOGFILE");
34 }
35 }
36
6484cc0f
TL
37 fn flush(&self) {
38 LOGFILE
39 .get()
40 .expect("could not get LOGFILE")
41 .lock()
42 .expect("could not get mutex for LOGFILE")
43 .flush()
44 .expect("could not flush LOGFILE");
45 }
c7edc2e1 46}