Allow reuse of previous logger.

This commit is contained in:
Gav Wood 2016-12-11 13:35:00 +01:00
parent 8d7a63bbea
commit 5bf9fa9168
No known key found for this signature in database
GPG Key ID: C49C1ACA1CC9B252

View File

@ -27,12 +27,12 @@ extern crate time;
extern crate lazy_static; extern crate lazy_static;
use std::{env, thread, fs}; use std::{env, thread, fs};
use std::sync::Arc; use std::sync::{Weak, Arc};
use std::io::Write; use std::io::Write;
use isatty::{stderr_isatty, stdout_isatty}; use isatty::{stderr_isatty, stdout_isatty};
use env_logger::LogBuilder; use env_logger::LogBuilder;
use regex::Regex; use regex::Regex;
use util::RotatingLogger; use util::{Mutex, RotatingLogger} ;
use util::log::Colour; use util::log::Colour;
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Clone)]
@ -52,6 +52,10 @@ impl Default for Config {
} }
} }
lazy_static! {
static ref ROTATING_LOGGER : Mutex<Weak<RotatingLogger>> = Mutex::new(Default::default());
}
/// Sets up the logger /// Sets up the logger
pub fn setup_log(config: &Config) -> Result<Arc<RotatingLogger>, String> { pub fn setup_log(config: &Config) -> Result<Arc<RotatingLogger>, String> {
use rlog::*; use rlog::*;
@ -121,9 +125,17 @@ pub fn setup_log(config: &Config) -> Result<Arc<RotatingLogger>, String> {
}; };
builder.format(format); builder.format(format);
builder.init().expect("Logger initialized only once."); builder.init()
.and_then(|_| {
Ok(logs) *ROTATING_LOGGER.lock() = Arc::downgrade(&logs);
Ok(logs)
})
// couldn't create new logger - try to fall back on previous logger.
.or_else(|err| match ROTATING_LOGGER.lock().upgrade() {
Some(l) => Ok(l),
// no previous logger. fatal.
None => Err(format!("{:?}", err)),
})
} }
fn kill_color(s: &str) -> String { fn kill_color(s: &str) -> String {