packager/pkgr/src/logging.rs

66 lines
2.2 KiB
Rust
Raw Normal View History

2023-07-17 21:23:59 +02:00
use colored::Colorize;
use fern::Dispatch;
2023-07-19 16:15:26 +02:00
use log::{Record, SetLoggerError};
use std::env;
2023-07-19 16:15:26 +02:00
fn format_regular<S: Into<String>>(log: S, record: &Record) -> String {
let log = log.into();
let line_prefix = |line: String, extend: bool| {
let prefix = if extend {
match record.level() {
log::Level::Trace => " :".bright_blue(),
log::Level::Debug => " :".green(),
log::Level::Info => " :".blue(),
log::Level::Warn => " :".yellow(),
log::Level::Error => " :".red(),
}.to_string()
} else {
match record.level() {
log::Level::Trace => "[TRACE]".bright_blue(),
log::Level::Debug => "??".green(),
log::Level::Info => "=>".blue(),
log::Level::Warn => "##".yellow(),
log::Level::Error => "!!".red()
}.to_string()
};
return format!("{} {}", prefix, line);
};
let mut lines = log.lines().peekable();
let mut output = match lines.peek() {
2023-08-01 21:33:32 +02:00
Some(_line) => line_prefix(lines.next().unwrap().to_string(), false),
2023-07-19 16:15:26 +02:00
None => return "".to_string(),
};
for line in lines {
output.push_str(&*format!("\n{}", line_prefix(line.to_string(), true)));
}
output
}
pub fn setup_logger() -> Result<(), SetLoggerError> {
Dispatch::new()
.format(|out, message, record| {
match record.metadata().target() {
"command:stdout" => {
2023-07-19 16:15:26 +02:00
out.finish(format_args!("{} {}", ">>".cyan(), message.to_string()));
return;
}
"command:stderr" => {
2023-07-19 16:15:26 +02:00
out.finish(format_args!("{} {}", ">>".red(), message.to_string()));
return;
}
2023-07-19 16:15:26 +02:00
_ => out.finish(format_args!("{}", format_regular(message.to_string(), record))),
}
})
2023-07-17 21:23:59 +02:00
.level(
env::var("PKGR_LOG_LEVEL")
.unwrap_or_else(|_| "info".to_string())
.parse()
.unwrap_or(log::LevelFilter::Info),
)
.chain(std::io::stdout())
.apply()
}