Skip to content

Commit

Permalink
refactor: improve logging
Browse files Browse the repository at this point in the history
  • Loading branch information
hulxv committed Jul 20, 2022
1 parent 0c098e0 commit f44d607
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 39 deletions.
84 changes: 45 additions & 39 deletions app/src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ impl Logger {
let mut log_builder = Builder::from_env(env_logger::Env::new().default_filter_or("info"));
log_builder
.format(|buf, record| {
let is_systemd_style = std::env::var("SYSTEMD_EXEC_PID").is_ok();
let logging_style =
std::env::var("VNS_LOGGIN_STYLE").unwrap_or("NORMAL".to_owned());

let mut level_style = buf.style();
let mut time_style = buf.style();
Expand All @@ -22,48 +23,53 @@ impl Logger {
_ => Color::Yellow,
});
time_style.set_color(Color::Rgb(255, 165, 0));
if is_systemd_style {
writeln!(
buf,
"<{}>{}: {}",
match record.level() {
log::Level::Error => 3,
log::Level::Warn => 4,
log::Level::Info => 6,
log::Level::Debug => 7,
log::Level::Trace => 7,
},
record.target(),
record.args()
)
.unwrap();
} else {
match record.level().eq(&Level::Error) {
// Write to stderr
true => eprintln!(
"{} {} : {} \n\t {} \n\t {}",
buf.timestamp().to_string().color(RGB::new(255, 165, 0)),
record.level().to_string().red(),
record.args().to_string().trim(),
format!("target: {}", record.target()),
format!(
"file: {} ({})",
record.file().unwrap(),
record.line().unwrap().to_string().yellow()
),
),

// Write to stdout (default)
_ => writeln!(
match logging_style.as_str() {
"SYSTEMD" => {
writeln!(
buf,
"⌜{}⌟{ } : {}",
time_style.value(buf.timestamp()),
level_style.value(record.level()),
record.args().to_string().trim()
"<{}>{}: {}",
match record.level() {
log::Level::Error => 3,
log::Level::Warn => 4,
log::Level::Info => 6,
log::Level::Debug => 7,
log::Level::Trace => 7,
},
record.target(),
record.args()
)
.unwrap(),
.unwrap();
}
}
_ => {
match record.level().eq(&Level::Error) {
// Write to stderr
true => eprintln!(
"⌜{}⌟ {} : {} \n\t {} \n\t {}",
buf.timestamp().to_string().color(RGB::new(255, 165, 0)),
record.level().to_string().red(),
record.args().to_string().trim(),
format!("target: {}", record.target()),
format!(
"file: {} ({})",
record.file().unwrap(),
record.line().unwrap().to_string().yellow()
),
),

// Write to stdout (default)
_ => writeln!(
buf,
"⌜{}⌟{ } : {}",
time_style.value(buf.timestamp()),
level_style.value(record.level()),
record.args().to_string().trim()
)
.unwrap(),
}
}
};

Ok(())
})
.target(Stdout)
Expand Down
1 change: 1 addition & 0 deletions systemd/vnstat-server.service
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ ProtectSystem=yes
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
Environment=VNS_LOGGIN_STYLE=SYSTEMD

[Install]
WantedBy=multi-user.target
Expand Down

0 comments on commit f44d607

Please sign in to comment.