use env_logger::{Builder, Env};
use log::{error, info, warn};
use std::fs::OpenOptions;
use std::io::Write;
pub struct LogUtil;
impl LogUtil {
pub fn init(&self, log_file_path: &str) {
let mut file = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(log_file_path).expect("Failed to create log file");
let env = Env::default().filter_or("RUST_LOG", "info");
Builder::from_env(env)
.format(|buf, record| {
writeln!(
buf,
"[{}][{}] {}",
chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f"),
record.level(),
record.args()
)
})
.target(env_logger::Target::Pipe(
Box::new(file) as Box<dyn std::io::Write + Send + 'static>
))
.init();
}
pub fn info(&self, message: &str) {
info!("{}", message);
}
pub fn error(&self, message: &str) {
error!("{}", message);
}
pub fn warn(&self, message: &str) {
warn!("{}", message);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let log_util = LogUtil;
log_util.init("app.log");
log_util.info("This is an info log");
log_util.warn("This is a warning log");
log_util.error("This is an error log");
}
}