Skip to content

Commit 338f4e9

Browse files
committed
logging: bugfix #137: Init log module to enable logging macros
1 parent c6ff2af commit 338f4e9

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-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: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,13 @@
2222
#![feature(panic_info_message)]
2323

2424
use core::arch::global_asm;
25+
use log::*;
2526
#[macro_use]
2627
mod console;
2728
mod config;
2829
mod lang_items;
2930
mod loader;
31+
mod logging;
3032
mod sbi;
3133
mod sync;
3234
pub mod syscall;
@@ -52,7 +54,8 @@ fn clear_bss() {
5254
#[no_mangle]
5355
pub fn rust_main() -> ! {
5456
clear_bss();
55-
println!("[kernel] Hello, world!");
57+
logging::init();
58+
info!("[kernel] Hello, world!");
5659
trap::init();
5760
loader::load_apps();
5861
task::run_first_task();

0 commit comments

Comments
 (0)