Skip to content

Commit

Permalink
new: Add colored log levels
Browse files Browse the repository at this point in the history
  • Loading branch information
camnwalter committed May 4, 2024
1 parent a8d1dd5 commit 763f7c5
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions src/logging.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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
Expand Down

0 comments on commit 763f7c5

Please sign in to comment.