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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
mod config;
pub use config::{LoggerConfig, LoggerConfigBuilder, LoggerOutputConfig, LoggerOutputConfigBuilder};
use fern::{
colors::{Color, ColoredLevelConfig},
Dispatch,
};
use thiserror::Error;
pub const LOGGER_STDOUT_NAME: &str = "stdout";
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error("Creating output file failed.")]
CreatingFileFailed,
#[error("Initializing the logger backend failed.")]
InitializationFailed,
}
macro_rules! log_format {
($target:expr, $level:expr, $message:expr) => {
format_args!(
"{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
$target,
$level,
$message
)
};
}
pub fn logger_init(config: LoggerConfig) -> Result<(), Error> {
let mut logger = if config.color_enabled {
let colors = ColoredLevelConfig::new()
.trace(Color::BrightMagenta)
.debug(Color::BrightBlue)
.info(Color::BrightGreen)
.warn(Color::BrightYellow)
.error(Color::BrightRed);
Dispatch::new().format(move |out, message, record| {
out.finish(log_format!(record.target(), colors.color(record.level()), message))
})
} else {
Dispatch::new()
.format(move |out, message, record| out.finish(log_format!(record.target(), record.level(), message)))
};
for output in config.outputs {
let mut dispatch = Dispatch::new().level(output.level);
dispatch = if output.name == LOGGER_STDOUT_NAME {
dispatch.chain(std::io::stdout())
} else {
dispatch.chain(fern::log_file(output.name).map_err(|_| Error::CreatingFileFailed)?)
};
logger = logger.chain(dispatch);
}
logger.apply().map_err(|_| Error::InitializationFailed)?;
Ok(())
}