1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
use log::{self, Log};
use std::cell::RefCell;
use std::sync;
use stderrlog::StdErrLog;
thread_local! {
pub static LOGGER_INSTANCE: RefCell<Option<StdErrLog>> = RefCell::new(None);
}
static INIT_LOGGER: sync::Once = sync::Once::new();
struct DelegatingLogger;
impl Log for DelegatingLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
LOGGER_INSTANCE.with(|instance| {
let instance = instance.borrow();
if let Some(ref instance) = *instance {
instance.enabled(metadata)
} else {
false
}
})
}
fn log(&self, record: &log::Record) {
LOGGER_INSTANCE.with(|instance| {
let instance = instance.borrow();
if let Some(ref instance) = *instance {
instance.log(record);
}
});
}
fn flush(&self) {
LOGGER_INSTANCE.with(|instance| {
let instance = instance.borrow();
if let Some(ref instance) = *instance {
instance.flush();
}
});
}
}
pub fn init() {
INIT_LOGGER.call_once(|| {
log::set_max_level(log::LevelFilter::max());
log::set_boxed_logger(Box::new(DelegatingLogger)).unwrap();
});
}
pub fn set_logger(logger: StdErrLog) {
LOGGER_INSTANCE.with(|instance| {
let mut instance = instance.borrow_mut();
*instance = Some(logger);
});
}
|