2018-08-04 08:28:13 +02:00
|
|
|
//! Contains functions to help with logging.
|
|
|
|
|
|
|
|
use chrono;
|
2018-08-04 09:03:32 +02:00
|
|
|
use fern;
|
2018-08-04 08:28:13 +02:00
|
|
|
use log;
|
|
|
|
|
2018-08-04 09:03:32 +02:00
|
|
|
use std::fmt::Debug;
|
2018-08-04 08:28:13 +02:00
|
|
|
use std::io;
|
|
|
|
|
|
|
|
pub fn setup_logger() -> Result<(), fern::InitError> {
|
|
|
|
fern::Dispatch::new()
|
|
|
|
.format(|out, message, record| {
|
|
|
|
out.finish(format_args!(
|
|
|
|
"{}[{}][{}] {}",
|
|
|
|
chrono::Local::now().format("[%H:%M:%S]"),
|
|
|
|
record.target(),
|
|
|
|
record.level(),
|
|
|
|
message
|
|
|
|
))
|
|
|
|
})
|
|
|
|
.level(log::LevelFilter::Info)
|
|
|
|
.chain(io::stdout())
|
|
|
|
.chain(fern::log_file("installer.log")?)
|
|
|
|
.apply()?;
|
|
|
|
Ok(())
|
|
|
|
}
|
2018-08-04 09:03:32 +02:00
|
|
|
|
|
|
|
/// An additional wrapper usable on Result/Option types to add logging to the regular
|
|
|
|
/// panic route.
|
|
|
|
pub trait LoggingErrors<T>
|
|
|
|
where
|
|
|
|
Self: Sized,
|
|
|
|
{
|
|
|
|
/// Unwraps this object. See `unwrap()`.
|
2018-08-04 09:12:00 +02:00
|
|
|
#[inline]
|
2018-08-04 09:03:32 +02:00
|
|
|
fn log_unwrap(self) -> T {
|
|
|
|
self.log_expect("Failed to unwrap")
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Unwraps this object, with a specified error message on failure. See `expect()`.
|
2018-08-04 09:12:00 +02:00
|
|
|
#[inline]
|
2018-08-04 09:03:32 +02:00
|
|
|
fn log_expect(self, msg: &str) -> T;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T, E: Debug> LoggingErrors<T> for Result<T, E> {
|
|
|
|
fn log_expect(self, msg: &str) -> T {
|
|
|
|
match self {
|
|
|
|
Ok(v) => v,
|
|
|
|
Err(v) => {
|
|
|
|
error!("Fatal error: {}: {:?}", msg, v);
|
|
|
|
panic!("Expectation failed");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> LoggingErrors<T> for Option<T> {
|
|
|
|
fn log_expect(self, msg: &str) -> T {
|
|
|
|
match self {
|
|
|
|
Some(v) => v,
|
|
|
|
None => {
|
|
|
|
error!("Fatal error: {}", msg);
|
|
|
|
panic!("Expectation failed");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|