use crate::shellexpand::ShellExpandTrait;
use std::fs::OpenOptions;
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
#[derive(Copy, Clone, PartialEq, PartialOrd, Hash, Debug)]
pub enum LoggingLevel {
OFF,
FATAL,
ERROR,
WARN,
INFO,
DEBUG,
TRACE,
}
impl std::fmt::Display for LoggingLevel {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{}",
match self {
OFF => "OFF",
FATAL => "FATAL",
ERROR => "ERROR",
WARN => "WARN",
INFO => "INFO",
DEBUG => "DEBUG",
TRACE => "TRACE",
}
)
}
}
use LoggingLevel::*;
struct LoggingBackend {
dest: BufWriter<std::fs::File>,
level: LoggingLevel,
}
thread_local!(static LOG: Arc<Mutex<LoggingBackend>> = Arc::new(Mutex::new({
let data_dir = xdg::BaseDirectories::with_prefix("meli").unwrap();
let log_file = OpenOptions::new().append(true)
.create(true)
.read(true)
.open(data_dir.place_data_file("meli.log").unwrap()).unwrap();
LoggingBackend {
dest: BufWriter::new(log_file),
level: INFO,
}
})));
pub fn log(val: String, level: LoggingLevel) {
LOG.with(|f| {
let mut b = f.lock().unwrap();
if level <= b.level {
b.dest
.write_all(
crate::datetime::timestamp_to_string(crate::datetime::now(), None).as_bytes(),
)
.unwrap();
b.dest.write_all(b" [").unwrap();
b.dest.write_all(level.to_string().as_bytes()).unwrap();
b.dest.write_all(b"]: ").unwrap();
b.dest.write_all(val.as_bytes()).unwrap();
b.dest.write_all(b"\n").unwrap();
b.dest.flush().unwrap();
}
});
}
pub fn get_log_level() -> LoggingLevel {
let mut level = INFO;
LOG.with(|f| {
level = f.lock().unwrap().level;
});
level
}
pub fn change_log_dest(path: PathBuf) {
LOG.with(|f| {
let path = path.expand(); let mut backend = f.lock().unwrap();
backend.dest = BufWriter::new(OpenOptions::new().append(true)
.create(true)
.read(true)
.open(path).unwrap());
});
}
pub fn change_log_level(new_val: LoggingLevel) {
LOG.with(|f| {
let mut backend = f.lock().unwrap();
backend.level = new_val;
});
}