|
| 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 | +} |
0 commit comments