Add ANSI colors to log levels: red E, yellow W, green I, cyan D

This commit is contained in:
Rodrigo Rodriguez (Pragmatismo) 2026-01-14 09:33:03 -03:00
parent 8526b0d585
commit 628f853c85

View file

@ -2,13 +2,20 @@ use env_logger::fmt::Formatter;
use log::Record;
use std::io::Write;
// ANSI color codes
const RED: &str = "\x1b[31m";
const YELLOW: &str = "\x1b[33m";
const GREEN: &str = "\x1b[32m";
const CYAN: &str = "\x1b[36m";
const RESET: &str = "\x1b[0m";
pub fn compact_format(buf: &mut Formatter, record: &Record) -> std::io::Result<()> {
let level = match record.level() {
log::Level::Error => "E",
log::Level::Warn => "W",
log::Level::Info => "I",
log::Level::Debug => "D",
log::Level::Trace => "T",
let (level, color) = match record.level() {
log::Level::Error => ("E", RED),
log::Level::Warn => ("W", YELLOW),
log::Level::Info => ("I", GREEN),
log::Level::Debug => ("D", CYAN),
log::Level::Trace => ("T", ""),
};
let now = chrono::Local::now();
@ -21,7 +28,11 @@ pub fn compact_format(buf: &mut Formatter, record: &Record) -> std::io::Result<(
target
};
writeln!(buf, "{} {} {}:{}", timestamp, level, module, record.args())
if color.is_empty() {
writeln!(buf, "{} {} {}:{}", timestamp, level, module, record.args())
} else {
writeln!(buf, "{} {}{}{} {}:{}", timestamp, color, level, RESET, module, record.args())
}
}
pub fn init_compact_logger(default_filter: &str) {