Add logger with logging library

This commit is contained in:
Matthias Beyer 2015-10-26 20:53:12 +01:00
parent f7421cf252
commit c41ec1d85c
2 changed files with 56 additions and 1 deletions

View file

@ -1,7 +1,8 @@
#[macro_use] extern crate clap;
#[macro_use] extern crate log;
use cli::Config;
use runtime::Runtime;
use runtime::{ImagLogger, Runtime};
use clap::App;
mod cli;
@ -10,10 +11,12 @@ mod module;
mod storage;
fn main() {
let early_logger = ImagLogger::early().unwrap();
let yaml = load_yaml!("../etc/cli.yml");
let app = App::from_yaml(yaml);
let mut config = Config::new(app);
let logger = ImagLogger::init(&config);
let rt = Runtime::new(config);
println!("Hello, world!");

View file

@ -1,7 +1,59 @@
extern crate log;
pub use cli::Config;
use std::io::stderr;
use std::io::Write;
use log::{LogRecord, LogLevel, LogLevelFilter, LogMetadata, SetLoggerError};
pub struct ImagLogger {
lvl: LogLevel,
}
impl ImagLogger {
pub fn new(lvl: LogLevel) -> ImagLogger {
ImagLogger {
lvl: lvl,
}
}
pub fn early() -> Result<(), SetLoggerError> {
ImagLogger::init_logger(LogLevelFilter::Error)
}
pub fn init(config: &Config) -> Result<(), SetLoggerError> {
if config.is_debugging() {
ImagLogger::init_logger(LogLevelFilter::Debug)
} else if config.is_verbose() {
ImagLogger::init_logger(LogLevelFilter::Info)
} else {
ImagLogger::init_logger(LogLevelFilter::Error)
}
}
fn init_logger(lvlflt : LogLevelFilter) -> Result<(), SetLoggerError> {
log::set_logger(|max_log_lvl| {
max_log_lvl.set(lvlflt);
Box::new(ImagLogger::new(lvlflt.to_log_level().unwrap()))
})
}
}
impl log::Log for ImagLogger {
fn enabled(&self, metadata: &LogMetadata) -> bool {
metadata.level() <= self.lvl
}
fn log(&self, record: &LogRecord) {
if self.enabled(record.metadata()) {
println!("[{}]: {}", record.level(), record.args());
}
}
}
pub struct Runtime<'a> {
pub config : Config<'a>,