Log to stdout and the file the binary needs to set up. This is a first variant. By using the log crate macros we can change that in the future without too much effort.
Tested-by: Christoph Heiss <c.he...@proxmox.com> Reviewed-by: Christoph Heiss <c.he...@proxmox.com> Signed-off-by: Aaron Lauterer <a.laute...@proxmox.com> --- proxmox-auto-installer/Cargo.toml | 2 ++ proxmox-auto-installer/src/lib.rs | 1 + proxmox-auto-installer/src/log.rs | 38 +++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 proxmox-auto-installer/src/log.rs diff --git a/proxmox-auto-installer/Cargo.toml b/proxmox-auto-installer/Cargo.toml index 80de4fa..b1d3e7a 100644 --- a/proxmox-auto-installer/Cargo.toml +++ b/proxmox-auto-installer/Cargo.toml @@ -8,8 +8,10 @@ exclude = [ "build", "debian" ] homepage = "https://www.proxmox.com" [dependencies] +anyhow = "1.0" proxmox-installer-common = { path = "../proxmox-installer-common" } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" toml = "0.7" enum-iterator = "0.6.0" +log = "0.4.20" diff --git a/proxmox-auto-installer/src/lib.rs b/proxmox-auto-installer/src/lib.rs index 72884c1..6636cc7 100644 --- a/proxmox-auto-installer/src/lib.rs +++ b/proxmox-auto-installer/src/lib.rs @@ -1,3 +1,4 @@ pub mod answer; +pub mod log; pub mod udevinfo; pub mod utils; diff --git a/proxmox-auto-installer/src/log.rs b/proxmox-auto-installer/src/log.rs new file mode 100644 index 0000000..d52912a --- /dev/null +++ b/proxmox-auto-installer/src/log.rs @@ -0,0 +1,38 @@ +use anyhow::{bail, Result}; +use log::{Level, Metadata, Record}; +use std::{fs::File, io::Write, sync::Mutex, sync::OnceLock}; + +pub struct AutoInstLogger; +static LOGFILE: OnceLock<Mutex<File>> = OnceLock::new(); + +impl AutoInstLogger { + pub fn init(path: &str) -> Result<()> { + let f = File::create(path)?; + if LOGFILE.set(Mutex::new(f)).is_err() { + bail!("Cannot set LOGFILE") + } + Ok(()) + } +} + +impl log::Log for AutoInstLogger { + fn enabled(&self, metadata: &Metadata) -> bool { + metadata.level() <= Level::Info + } + + /// Logs to stdout without log level and into log file including log level + fn log(&self, record: &Record) { + if self.enabled(record.metadata()) { + println!("{}", record.args()); + let mut file = LOGFILE + .get() + .expect("could not get LOGFILE") + .lock() + .expect("could not get mutex for LOGFILE"); + file.write_all(format!("{} - {}\n", record.level(), record.args()).as_bytes()) + .expect("could not write to LOGFILE"); + } + } + + fn flush(&self) {} +} -- 2.39.2 _______________________________________________ pve-devel mailing list pve-devel@lists.proxmox.com https://lists.proxmox.com/cgi-bin/mailman/listinfo/pve-devel