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
//! This crate contains the beauty logger.
//!
//! It is made to be super simple and to mimic the output of rustup and cargo.
//! ### Usage:
//! ```
//! #[macro_use]
//! extern crate log;
//!
//! fn main() {
//!
//!     beautylog::init(log::LevelFilter::Trace).ok();
//!
//!     info!("some information");
//!     warn!("something went wrong");
//!     debug!("some debug info");
//!     trace!("yo");
//!     error!("something went horribly wrong");
//!
//! }
//! ```
//!
//! ### How it looks like
//! ![how it renders](https://gitea.tforgione.fr/attachments/3417667c-746d-4f7f-bb79-c4ffa4913281)
//!

use log::{Record, Level, Metadata, SetLoggerError, LevelFilter};
use colored::*;

struct BeautyLogger;
static LOGGER: BeautyLogger = BeautyLogger;

/// Initializes the beauty logger with the corresponding level filter.
pub fn init(level: LevelFilter) -> Result<(), SetLoggerError> {
    log::set_logger(&LOGGER)
        .map(|()| log::set_max_level(level))
}

impl log::Log for BeautyLogger {
    fn enabled(&self, _: &Metadata) -> bool {
        true
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            match record.level() {
                Level::Error => eprintln!("{} {}", "error:".bold().red(), record.args()),
                Level::Warn  => eprintln!("{} {}", "warning:".bold().yellow(), record.args()),
                Level::Info  => eprintln!("{} {}", "info:".bold(), record.args()),
                Level::Debug => eprintln!("{} {}", "debug:".bold().blue(), record.args()),
                Level::Trace => eprintln!("{} {}", "trace:".bold().cyan(), record.args()),
            }
        }
    }

    fn flush(&self) {}
}