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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
pub use log::LevelFilter;
use log::debug;
use serde::{Deserialize, Serialize};
use std::{env, fmt, io, path::PathBuf, str::FromStr};
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum StdoutLog {
Off,
Plain,
Colored,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LoggerConfig {
pub stdout: StdoutLog,
pub level_filter: LevelFilter,
pub log_file: Option<PathBuf>,
pub allow_env_override: bool,
pub log_gfx_device_level: Option<LevelFilter>,
}
impl Default for LoggerConfig {
fn default() -> Self {
Self {
stdout: StdoutLog::Colored,
level_filter: LevelFilter::Info,
log_file: None,
allow_env_override: true,
log_gfx_device_level: Some(LevelFilter::Warn),
}
}
}
#[allow(missing_debug_implementations)]
pub struct Logger {
dispatch: fern::Dispatch,
}
impl Logger {
fn new() -> Self {
let dispatch = fern::Dispatch::new().format(|out, message, record| {
out.finish(format_args!(
"[{level}][{target}] {message}",
level = record.level(),
target = record.target(),
message = message,
))
});
Self { dispatch }
}
fn new_formatter<F>(formatter: F) -> Self
where
F: Fn(fern::FormatCallback<'_>, &fmt::Arguments<'_>, &log::Record<'_>)
+ Sync
+ Send
+ 'static,
{
let dispatch = fern::Dispatch::new().format(formatter);
Self { dispatch }
}
fn new_with_config(mut config: LoggerConfig, mut logger: Self) -> Self {
if config.allow_env_override {
env_var_override(&mut config);
}
logger.dispatch = logger.dispatch.level(config.level_filter);
match config.stdout {
StdoutLog::Plain => logger.dispatch = logger.dispatch.chain(io::stdout()),
StdoutLog::Colored => {
logger.dispatch = logger
.dispatch
.chain(colored_stdout(fern::colors::ColoredLevelConfig::new()))
}
StdoutLog::Off => {}
}
if let Some(log_gfx_device_level) = config.log_gfx_device_level {
logger.dispatch = logger
.dispatch
.level_for("gfx_device_gl", log_gfx_device_level);
}
if let Some(path) = config.log_file {
if let Ok(log_file) = fern::log_file(path) {
logger.dispatch = logger.dispatch.chain(log_file)
} else {
eprintln!("Unable to access the log file, as such it will not be used")
}
}
logger
}
pub fn from_config(config: LoggerConfig) -> Self {
Logger::new_with_config(config, Logger::new())
}
pub fn from_config_formatter<F>(config: LoggerConfig, formatter: F) -> Self
where
F: Fn(fern::FormatCallback<'_>, &fmt::Arguments<'_>, &log::Record<'_>)
+ Sync
+ Send
+ 'static,
{
Logger::new_with_config(config, Logger::new_formatter(formatter))
}
pub fn level_for<T: Into<std::borrow::Cow<'static, str>>>(
mut self,
module: T,
level: LevelFilter,
) -> Self {
self.dispatch = self.dispatch.level_for(module, level);
self
}
pub fn start(self) {
self.dispatch.apply().unwrap_or_else(|_| {
debug!("Global logger already set, default Amethyst logger will not be used")
});
}
}
pub fn start_logger(config: LoggerConfig) {
Logger::from_config(config).start();
}
fn env_var_override(config: &mut LoggerConfig) {
if let Ok(var) = env::var("AMETHYST_LOG_STDOUT") {
match var.to_lowercase().as_ref() {
"off" | "no" | "0" => config.stdout = StdoutLog::Off,
"plain" | "yes" | "1" => config.stdout = StdoutLog::Plain,
"colored" | "2" => config.stdout = StdoutLog::Colored,
_ => {}
}
}
if let Ok(var) = env::var("AMETHYST_LOG_LEVEL_FILTER") {
if let Ok(lf) = LevelFilter::from_str(&var) {
config.level_filter = lf;
}
}
if let Ok(path) = env::var("AMETHYST_LOG_FILE_PATH") {
config.log_file = Some(PathBuf::from(path));
}
}
fn colored_stdout(color_config: fern::colors::ColoredLevelConfig) -> fern::Dispatch {
fern::Dispatch::new()
.chain(io::stdout())
.format(move |out, message, record| {
let color = color_config.get_color(&record.level());
out.finish(format_args!(
"{color}{message}{color_reset}",
color = format!("\x1B[{}m", color.to_fg_str()),
message = message,
color_reset = "\x1B[0m",
))
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
#[test]
fn check_stdout_override() {
let mut config = LoggerConfig::default();
assert_eq!(config.stdout, StdoutLog::Colored);
env::set_var("AMETHYST_LOG_STDOUT", "pLaIn");
env_var_override(&mut config);
env::remove_var("AMETHYST_LOG_STDOUT");
assert_eq!(config.stdout, StdoutLog::Plain);
}
}