Skip to content

Commit

Permalink
Merge pull request #1171 from camnwalter/color-logging
Browse files Browse the repository at this point in the history
new: Add colored log levels
  • Loading branch information
mkroening authored May 4, 2024
2 parents a8d1dd5 + 7797897 commit 87ebdd3
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
1 change: 1 addition & 0 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 @@ -102,6 +102,7 @@ async-trait = "0.1.80"
async-lock = { version = "3.3.0", default-features = false }
simple-shell = { version = "0.0.1", optional = true }
volatile = "0.5.4"
anstyle = { version = "1", default-features = false }

[dependencies.smoltcp]
version = "0.11"
Expand Down
34 changes: 32 additions & 2 deletions src/logging.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use log::{LevelFilter, Metadata, Record};
use core::fmt;

use anstyle::AnsiColor;
use log::{Level, LevelFilter, Metadata, Record};

/// Data structure to filter kernel messages
struct KernelLogger;
Expand All @@ -17,13 +20,40 @@ 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 = self.0;

if no_color() {
write!(f, "{level}")
} else {
let color = match level {
Level::Trace => AnsiColor::Magenta,
Level::Debug => AnsiColor::Blue,
Level::Info => AnsiColor::Green,
Level::Warn => AnsiColor::Yellow,
Level::Error => AnsiColor::Red,
};

let style = anstyle::Style::new().fg_color(Some(color.into()));
write!(f, "{style}{level}{style:#}")
}
}
}

fn no_color() -> bool {
option_env!("NO_COLOR").is_some_and(|val| !val.is_empty())
}

pub unsafe fn init() {
log::set_logger(&KernelLogger).expect("Can't initialize logger");
// Determines LevelFilter at compile time
Expand Down

0 comments on commit 87ebdd3

Please sign in to comment.