diff --git a/src/logging.rs b/src/logging.rs index 905268a9ba..5170375684 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -1,4 +1,6 @@ -use log::{LevelFilter, Metadata, Record}; +use core::fmt; + +use log::{Level, LevelFilter, Metadata, Record}; /// Data structure to filter kernel messages struct KernelLogger; @@ -17,13 +19,37 @@ impl log::Log for KernelLogger { println!( "[{}][{}] {}", crate::arch::core_local::core_id(), - record.level(), + ColorLevel(record.level()), record.args() ); } } } +struct ColorLevel(Level); + +impl fmt::Display for ColorLevel { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let level: Level = self.0; + let color_code: &str = match level { + Level::Error => "\x1b[31m", // red + Level::Debug => "\x1b[34m", // blue + Level::Trace => "\x1b[35m", // magenta + Level::Info => "\x1b[32m", // green + Level::Warn => "\x1b[33m", // yellow + }; + let reset_color: &str = "\x1b[0m"; + + let no_color: Option<&'static str> = option_env!("NO_COLOR"); + + if no_color.is_some_and(|c| !c.is_empty()) { + write!(f, "{level}") + } else { + write!(f, "{color_code}{}{reset_color}", level.as_str()) + } + } +} + pub unsafe fn init() { log::set_logger(&KernelLogger).expect("Can't initialize logger"); // Determines LevelFilter at compile time