Skip to content

Commit

Permalink
new: Add colored log levels
Browse files Browse the repository at this point in the history
Signed-off-by: Cam Walter <[email protected]>
  • Loading branch information
camnwalter committed May 5, 2024
1 parent 8efb4f0 commit 53c1ec7
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
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 @@ -15,6 +15,7 @@ one-shot-mutex = "0.1"
sptr = "0.3"
take-static = "0.1"
vm-fdt = { version = "0.3", default-features = false, features = ["alloc"] }
anstyle = { version = "1", default-features = false }

[features]
default = []
Expand Down
32 changes: 31 additions & 1 deletion src/log.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use core::fmt;

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

struct Logger;
Expand All @@ -12,7 +15,7 @@ impl log::Log for Logger {

fn log(&self, record: &Record<'_>) {
if self.enabled(record.metadata()) {
let level = record.level();
let level = ColorLevel(record.level());
let args = record.args();
println!("[LOADER][{level}] {args}");
}
Expand All @@ -21,6 +24,33 @@ impl log::Log for Logger {
fn flush(&self) {}
}

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 fn init() {
static LOGGER: Logger = Logger;
log::set_logger(&LOGGER).unwrap();
Expand Down

0 comments on commit 53c1ec7

Please sign in to comment.