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
|
|
|
|
))
|
2018-08-07 07:34:57 +02:00
|
|
|
})
|
|
|
|
.level(log::LevelFilter::Info)
|
2018-08-04 08:28:13 +02:00
|
|
|
.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-07 07:34:57 +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()`.
|
|
|
|
fn log_expect(self, msg: &str) -> T;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T, E: Debug> LoggingErrors<T> for Result<T, E> {
|
2018-08-07 07:34:57 +02:00
|
|
|
#[inline]
|
2018-08-04 09:03:32 +02:00
|
|
|
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> {
|
2018-08-07 07:34:57 +02:00
|
|
|
#[inline]
|
2018-08-04 09:03:32 +02:00
|
|
|
fn log_expect(self, msg: &str) -> T {
|
|
|
|
match self {
|
|
|
|
Some(v) => v,
|
|
|
|
None => {
|
|
|
|
error!("Fatal error: {}", msg);
|
|
|
|
panic!("Expectation failed");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|