1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use {
crate::{
file_logger::FileLogger,
},
log::{
LevelFilter,
},
std::{
env,
fs::File,
str::FromStr,
sync::Mutex,
},
};
pub fn init(app_name: &str, app_version: &str) {
let env_var_name = format!(
"{}_LOG",
app_name.to_ascii_uppercase().replace('-', "_"),
);
let level = env::var(&env_var_name).unwrap_or_else(|_| "off".to_string());
if level == "off" {
return;
}
if let Ok(level) = LevelFilter::from_str(&level) {
let log_file_name = format!("{}.log", app_name);
let file = File::create(&log_file_name)
.expect("Log file can't be created");
log::set_max_level(level);
let logger = FileLogger {
file: Mutex::new(file),
level,
};
log::set_boxed_logger(Box::new(logger)).unwrap();
log::info!(
"Starting {} v{} with log level {}",
app_name,
app_version,
level
);
}
}
#[macro_export]
macro_rules! init_cli_log {
() => {
cli_log::init(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
};
($app_name: expr) => {
cli_log::init($app_name, env!("CARGO_PKG_VERSION"));
};
}