1use env_logger::{Builder, Env};
2use log::{error, info, warn};
3use std::fs::OpenOptions;
4use std::io::Write;
5
6pub struct LogUtil;
7
8impl LogUtil {
9 pub fn init(&self, log_file_path: &str) {
11 let file = OpenOptions::new()
12 .write(true)
13 .append(true)
14 .create(true)
15 .open(log_file_path).expect("Failed to create log file");
16 let env = Env::default().filter_or("RUST_LOG", "info");
17 Builder::from_env(env)
18 .format(|buf, record| {
19 writeln!(
20 buf,
21 "[{}][{}] {}",
22 chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f"),
23 record.level(),
24 record.args()
25 )
26 })
27 .target(env_logger::Target::Pipe(
28 Box::new(file) as Box<dyn std::io::Write + Send + 'static>
29 ))
30 .init();
31 }
32
33 pub fn info(&self, message: &str) {
37 info!("{}", message);
38 }
39
40 pub fn error(&self, message: &str) {
44 error!("{}", message);
45 }
46
47 pub fn warn(&self, message: &str) {
51 warn!("{}", message);
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58 #[test]
59 fn it_works() {
60 let log_util = LogUtil;
61 log_util.init("app.log");
62 log_util.info("This is an info log");
63 log_util.warn("This is a warning log");
64 log_util.error("This is an error log");
65 }
66}