parent
d1f45584de
commit
98389a33ec
@ -0,0 +1,93 @@
|
||||
use std::boxed::Box;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use colored::Colorize;
|
||||
use log::*;
|
||||
|
||||
use crate::result::Result;
|
||||
|
||||
static LOGGER: Logger = Logger;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum LoggerError {
|
||||
SetLogger(SetLoggerError),
|
||||
}
|
||||
|
||||
impl From<SetLoggerError> for LoggerError {
|
||||
fn from(e: SetLoggerError) -> Self {
|
||||
LoggerError::SetLogger(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for LoggerError {
|
||||
fn description(&self) -> &str {
|
||||
match *self {
|
||||
LoggerError::SetLogger(_) => "Logger already initialized",
|
||||
}
|
||||
}
|
||||
fn cause(&self) -> Option<&dyn Error> {
|
||||
match *self {
|
||||
LoggerError::SetLogger(_) => Some(self),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for LoggerError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
use std::error::Error as FmtError;
|
||||
write!(f, "{}", self.description())
|
||||
}
|
||||
}
|
||||
|
||||
struct Logger;
|
||||
|
||||
impl Log for Logger {
|
||||
fn enabled(&self, metadata: &Metadata) -> bool {
|
||||
metadata.level() <= Level::Trace
|
||||
}
|
||||
|
||||
fn log(&self, record: &Record) {
|
||||
if self.enabled(record.metadata()) {
|
||||
let now = chrono::Local::now();
|
||||
let ts = now.format("%Y-%m-%dT%H:%M:%S%.3f%z").to_string();
|
||||
|
||||
let (msg, _level) = match record.level() {
|
||||
Level::Error => (
|
||||
format!("{} {} {}", ts.white().bold(), "ERR".red(), record.args()),
|
||||
3,
|
||||
),
|
||||
Level::Warn => (
|
||||
format!("{} {} {}", ts.white().bold(), "WRN".purple(), record.args()),
|
||||
4,
|
||||
),
|
||||
Level::Info => (
|
||||
format!("{} {} {}", ts.white().bold(), "INF".cyan(), record.args()),
|
||||
6,
|
||||
),
|
||||
Level::Debug => (
|
||||
format!("{} {} {}", ts.white().bold(), "DBG".yellow(), record.args()),
|
||||
7,
|
||||
),
|
||||
Level::Trace => (
|
||||
format!("{} {} {}", ts.white().bold(), "TRC".green(), record.args()),
|
||||
0,
|
||||
),
|
||||
};
|
||||
println!("{}", msg);
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
pub fn init() -> Result<()> {
|
||||
match set_logger(&LOGGER).map(|()| set_max_level(LevelFilter::Info)) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(Box::new(LoggerError::from(e))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_level(level: LevelFilter) {
|
||||
set_max_level(level);
|
||||
}
|
Loading…
Reference in new issue