imag/libimagrt/src/logger.rs

90 lines
2.6 KiB
Rust
Raw Normal View History

use std::io::Write;
use std::io::stderr;
2016-01-10 14:04:06 +00:00
use log::{Log, LogLevel, LogRecord, LogMetadata};
use ansi_term::Style;
use ansi_term::Colour;
use ansi_term::ANSIString;
2016-01-10 14:04:06 +00:00
pub struct ImagLogger {
lvl: LogLevel,
color_enabled: bool,
2016-01-10 14:04:06 +00:00
}
impl ImagLogger {
pub fn new(lvl: LogLevel) -> ImagLogger {
ImagLogger {
lvl: lvl,
color_enabled: true
}
}
pub fn with_color(mut self, b: bool) -> ImagLogger {
self.color_enabled = b;
self
}
fn style_or_not(&self, c: Style, s: String) -> ANSIString {
if self.color_enabled {
c.paint(s)
} else {
ANSIString::from(s)
}
}
fn color_or_not(&self, c: Colour, s: String) -> ANSIString {
if self.color_enabled {
c.paint(s)
} else {
ANSIString::from(s)
2016-01-10 14:04:06 +00:00
}
}
}
impl Log for ImagLogger {
fn enabled(&self, metadata: &LogMetadata) -> bool {
metadata.level() <= self.lvl
}
fn log(&self, record: &LogRecord) {
use ansi_term::Colour::Red;
use ansi_term::Colour::Yellow;
use ansi_term::Colour::Cyan;
2016-01-10 14:04:06 +00:00
if self.enabled(record.metadata()) {
// TODO: This is just simple logging. Maybe we can enhance this lateron
let loc = record.location();
match record.metadata().level() {
LogLevel::Debug => {
let lvl = self.color_or_not(Cyan, format!("{}", record.level()));
let file = self.color_or_not(Cyan, format!("{}", loc.file()));
let ln = self.color_or_not(Cyan, format!("{}", loc.line()));
let args = self.color_or_not(Cyan, format!("{}", record.args()));
writeln!(stderr(), "[imag][{: <5}][{}][{: >5}]: {}", lvl, file, ln, args).ok();
},
LogLevel::Warn | LogLevel::Error => {
let lvl = self.style_or_not(Red.blink(), format!("{}", record.level()));
let args = self.color_or_not(Red, format!("{}", record.args()));
writeln!(stderr(), "[imag][{: <5}]: {}", lvl, args).ok();
},
LogLevel::Info => {
let lvl = self.color_or_not(Yellow, format!("{}", record.level()));
let args = self.color_or_not(Yellow, format!("{}", record.args()));
writeln!(stderr(), "[imag][{: <5}]: {}", lvl, args).ok();
},
_ => {
writeln!(stderr(), "[imag][{: <5}]: {}", record.level(), record.args()).ok();
},
}
2016-01-10 14:04:06 +00:00
}
}
}