Skip to content

Commit

Permalink
feat(cli): add console colors in local logger
Browse files Browse the repository at this point in the history
  • Loading branch information
adriencaccia committed Jul 15, 2024
1 parent 3ea75be commit bd3bc0e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 77 deletions.
73 changes: 4 additions & 69 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ serde_yaml = "0.9.34"
sysinfo = { version = "0.30.12", features = ["serde"] }
indicatif = "0.17.8"
atty = "0.2.14"
console = "0.15.8"

[dev-dependencies]
temp-env = { version = "0.3.6", features = ["async_closure"] }
Expand Down
34 changes: 26 additions & 8 deletions src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{
time::Duration,
};

use console::Style;
use indicatif::{ProgressBar, ProgressStyle};
use lazy_static::lazy_static;
use log::Log;
Expand Down Expand Up @@ -138,7 +139,7 @@ impl Log for LocalLogger {
let spinner = ProgressBar::new_spinner();
spinner.set_style(
ProgressStyle::with_template(
" {spinner:>.cyan} {wide_msg:.magenta.bold}",
" {spinner:>.cyan} {wide_msg:.cyan.bold}",
)
.unwrap(),
);
Expand All @@ -164,20 +165,37 @@ impl Log for LocalLogger {
return;
}

suspend_progress_bar(|| {
if record.level() == log::Level::Error {
eprintln!("{}", record.args());
} else {
println!("{}", record.args());
}
});
suspend_progress_bar(|| print_record(record));
}

fn flush(&self) {
std::io::stdout().flush().unwrap();
}
}

/// Print a log record to the console with the appropriate style
fn print_record(record: &log::Record) {
let error_style = Style::new().red();
let info_style = Style::new().white();
let warn_style = Style::new().yellow();
let debug_style = Style::new().blue().dim();
let trace_style = Style::new().black().dim();

match record.level() {
log::Level::Error => eprintln!("{}", error_style.apply_to(record.args())),
log::Level::Warn => eprintln!("{}", warn_style.apply_to(record.args())),
log::Level::Info => println!("{}", info_style.apply_to(record.args())),
log::Level::Debug => println!(
"{}",
debug_style.apply_to(format!("[DEBUG::{}] {}", record.target(), record.args())),
),
log::Level::Trace => println!(
"{}",
trace_style.apply_to(format!("[TRACE::{}] {}", record.target(), record.args()))
),
}
}

impl SharedLogger for LocalLogger {
fn level(&self) -> log::LevelFilter {
self.log_level
Expand Down

0 comments on commit bd3bc0e

Please sign in to comment.