Skip to content

Commit 6699e80

Browse files
committed
logging: bugfix #137: Init log module to enable logging macros
1 parent fcf104f commit 6699e80

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

os/src/logging.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*!
2+
3+
本模块利用 log crate 为你提供了日志功能,使用方式见 main.rs.
4+
5+
*/
6+
7+
use log::{self, Level, LevelFilter, Log, Metadata, Record};
8+
9+
struct SimpleLogger;
10+
11+
impl Log for SimpleLogger {
12+
fn enabled(&self, _metadata: &Metadata) -> bool {
13+
true
14+
}
15+
fn log(&self, record: &Record) {
16+
if !self.enabled(record.metadata()) {
17+
return;
18+
}
19+
let color = match record.level() {
20+
Level::Error => 31, // Red
21+
Level::Warn => 93, // BrightYellow
22+
Level::Info => 34, // Blue
23+
Level::Debug => 32, // Green
24+
Level::Trace => 90, // BrightBlack
25+
};
26+
println!(
27+
"\u{1B}[{}m[{:>5}] {}\u{1B}[0m",
28+
color,
29+
record.level(),
30+
record.args(),
31+
);
32+
}
33+
fn flush(&self) {}
34+
}
35+
36+
pub fn init() {
37+
static LOGGER: SimpleLogger = SimpleLogger;
38+
log::set_logger(&LOGGER).unwrap();
39+
log::set_max_level(match option_env!("LOG") {
40+
Some("ERROR") => LevelFilter::Error,
41+
Some("WARN") => LevelFilter::Warn,
42+
Some("INFO") => LevelFilter::Info,
43+
Some("DEBUG") => LevelFilter::Debug,
44+
Some("TRACE") => LevelFilter::Trace,
45+
_ => LevelFilter::Info,
46+
});
47+
}

os/src/main.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ extern crate alloc;
3131
#[macro_use]
3232
extern crate bitflags;
3333

34+
use log::*;
35+
3436
#[path = "boards/qemu.rs"]
3537
mod board;
3638

@@ -40,6 +42,7 @@ mod config;
4042
mod drivers;
4143
pub mod fs;
4244
pub mod lang_items;
45+
mod logging;
4346
pub mod mm;
4447
pub mod sbi;
4548
pub mod sync;
@@ -67,7 +70,8 @@ fn clear_bss() {
6770
/// the rust entry-point of os
6871
pub fn rust_main() -> ! {
6972
clear_bss();
70-
println!("[kernel] Hello, world!");
73+
logging::init();
74+
info!("[kernel] Hello, world!");
7175
mm::init();
7276
mm::remap_test();
7377
trap::init();

0 commit comments

Comments
 (0)