-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathlogger.rs
More file actions
69 lines (63 loc) · 2 KB
/
logger.rs
File metadata and controls
69 lines (63 loc) · 2 KB
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
use std::str::FromStr;
use tracing::warn;
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogFormat {
Pretty,
Json,
Compact,
}
impl FromStr for LogFormat {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"json" => Ok(Self::Json),
"compact" => Ok(Self::Compact),
"pretty" => Ok(Self::Pretty),
_ => {
warn!("Invalid log format '{}', defaulting to 'pretty'", s);
Ok(Self::Pretty)
}
}
}
}
pub fn init_logger_with_format(log_level: &str, format: LogFormat) {
let level = match log_level.to_lowercase().as_str() {
"trace" => tracing::Level::TRACE,
"debug" => tracing::Level::DEBUG,
"info" => tracing::Level::INFO,
"warn" => tracing::Level::WARN,
"error" => tracing::Level::ERROR,
_ => {
warn!("Invalid log level '{}', defaulting to 'info'", log_level);
tracing::Level::INFO
}
};
let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(level.to_string()));
match format {
LogFormat::Json => {
tracing_subscriber::registry()
.with(env_filter)
.with(
fmt::layer()
.json()
.flatten_event(true)
.with_current_span(true),
)
.init();
}
LogFormat::Compact => {
tracing_subscriber::registry()
.with(env_filter)
.with(fmt::layer().compact())
.init();
}
LogFormat::Pretty => {
tracing_subscriber::registry()
.with(env_filter)
.with(fmt::layer().pretty())
.init();
}
}
}