Adding simple logger implementation to use with log crate.
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
use log::{Level, Metadata, Record, SetLoggerError, LevelFilter};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::LazyLock;
|
||||
use time_format;
|
||||
|
||||
struct KiraLogger {
|
||||
file: Option<Mutex<File>>,
|
||||
}
|
||||
|
||||
impl KiraLogger {
|
||||
pub fn open(file_name: Option<&str>) -> std::io::Result<Self> {
|
||||
match file_name {
|
||||
Some(f_n) => Ok(Self {
|
||||
file: Some(Mutex::new(
|
||||
OpenOptions::new().append(true).create(true).open(f_n)?,
|
||||
)),
|
||||
}),
|
||||
None => Ok(Self {
|
||||
file: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl log::Log for KiraLogger {
|
||||
fn enabled(&self, metadata: &Metadata) -> bool {
|
||||
(metadata.target().starts_with("kira_installer") && metadata.level() <= Level::Debug) || (metadata.level() <= Level::Error)
|
||||
}
|
||||
|
||||
fn log(&self, record: &Record) {
|
||||
if self.enabled(record.metadata()) {
|
||||
let ts = time_format::now().unwrap();
|
||||
let local_time = time_format::strftime_local("%Y-%m-%dT%H:%M:%S", ts).unwrap();
|
||||
if let Some(m_file) = &self.file {
|
||||
|
||||
let mut write_lock = m_file.lock().unwrap();
|
||||
let _ = writeln!(&mut *write_lock, "{} {}: {}", local_time, record.level(), record.args());
|
||||
}
|
||||
println!("{} {} {}: {}", local_time,record.metadata().target(), record.level(), record.args());
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {
|
||||
if let Some(m_file) = &self.file {
|
||||
let mut write_lock = m_file.lock().unwrap();
|
||||
let _ = (&mut *write_lock).flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static LOGGER: LazyLock<KiraLogger> = LazyLock::new(|| {
|
||||
let ts = time_format::now().unwrap();
|
||||
// Local time with timezone name
|
||||
let local_time = time_format::strftime_local("%Y-%m-%d_%H-%M-%S", ts).unwrap();
|
||||
KiraLogger::open(Some(format!("installation_{}.log", local_time).as_str())).unwrap()
|
||||
});
|
||||
|
||||
pub fn init() -> Result<(), SetLoggerError> {
|
||||
log::set_logger(&*LOGGER)
|
||||
.map(|()| log::set_max_level(LevelFilter::Debug))
|
||||
}
|
||||
Reference in New Issue
Block a user