2017-04-09 10:04:28 +00:00
|
|
|
use log::{self, LogRecord, LogLevel, LogMetadata};
|
2017-03-17 10:03:07 +00:00
|
|
|
pub use log::SetLoggerError;
|
|
|
|
|
2017-03-18 16:22:11 +00:00
|
|
|
use ansi_term::{Color, Style};
|
2017-04-14 20:39:32 +00:00
|
|
|
use std::io::Write;
|
2017-03-18 16:22:11 +00:00
|
|
|
|
|
|
|
|
2017-04-14 20:39:32 +00:00
|
|
|
macro_rules! println_stderr(
|
|
|
|
($($arg:tt)*) => { {
|
|
|
|
let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
|
|
|
|
r.expect("failed printing to stderr");
|
|
|
|
} }
|
|
|
|
);
|
|
|
|
|
2017-04-09 10:04:28 +00:00
|
|
|
struct Logger(LogLevel);
|
2017-03-17 10:03:07 +00:00
|
|
|
|
|
|
|
impl log::Log for Logger {
|
|
|
|
fn enabled(&self, metadata: &LogMetadata) -> bool {
|
2017-04-09 10:04:28 +00:00
|
|
|
metadata.level() <= self.0
|
2017-03-17 10:03:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn log(&self, record: &LogRecord) {
|
|
|
|
if self.enabled(record.metadata()) {
|
2017-04-09 10:04:28 +00:00
|
|
|
match record.level() {
|
2017-04-14 20:39:32 +00:00
|
|
|
LogLevel::Error => println_stderr!("{}: {}", Color::Red.bold().paint("error"), record.args()),
|
|
|
|
LogLevel::Warn => println_stderr!("{}: {}", Color::Yellow.bold().paint("warning"), record.args()),
|
|
|
|
LogLevel::Info => println_stderr!("{}: {}", Color::Green.bold().paint("info"), record.args()),
|
|
|
|
LogLevel::Debug => println_stderr!("{}: {}", Style::new().bold().paint("debug"), record.args()),
|
|
|
|
LogLevel::Trace => println_stderr!("{}: {}", "trace", record.args())
|
2017-03-18 16:22:11 +00:00
|
|
|
}
|
2017-03-17 10:03:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-09 10:04:28 +00:00
|
|
|
pub fn init(level: LogLevel) -> Result<(), SetLoggerError> {
|
2017-03-17 10:03:07 +00:00
|
|
|
log::set_logger(|max_log_level| {
|
2017-04-09 10:04:28 +00:00
|
|
|
max_log_level.set(level.to_log_level_filter());
|
|
|
|
Box::new(Logger(level))
|
2017-03-17 10:03:07 +00:00
|
|
|
})
|
|
|
|
}
|