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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//! A basic log implementation
//!
//! Usage
//!
//! First, add the required dependencies to your `Cargo.toml`.
//! ```toml
//! [dependencies]
//! basic-logger = "0.1"
//! log = "0.4"
//! ```
//!
//! _Note:_ Coloured output will be enabled by default. You can remove this feature by disabling all features. E.g.
//! ```toml
//! [dependencies]
//! ...
//! basic-logger = { version = "0.1", default-features = false }
//! ```
//!
//! 2. Initialize the logger _(Do this as early as possible in your project)_
//! E.g.
//! ```rust
//! use basic_logger::BasicLogger;
//!
//! use log::info, warn;
//!
//! fn main() {
//!     BasicLogger::new().init().unwrap();
//!
//!     info!("Hello, world!");
//! }
//! ```

#[cfg(feature = "colored")]
use colored::Colorize;

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

/// Implements [`log`] and a set of builder methods for configuration.
///
/// Use the "builder" methods on this struct to configure the logger, then call [`init`] to initialize the actual logger.
pub struct BasicLogger {
    default_filter: LevelFilter,
}

impl BasicLogger {
    /// Initialize the logger with the default log level set to `Level::Trace`.
    pub fn new() -> Self {
        Self {
            default_filter: LevelFilter::Trace,
        }
    }

    /// Set the 'default' log level.
    #[must_use = "You must call init() to begin logging"]
    pub fn with_level(mut self, level: LevelFilter) -> Self {
        self.default_filter = level;

        self
    }

    /// Initialize the actual logger.
    pub fn init(self) -> Result<(), SetLoggerError> {
        log::set_max_level(self.default_filter);
        log::set_boxed_logger(Box::new(self))?;

        Ok(())
    }
}

impl Default for BasicLogger {
    /// See [this](struct.BasicLogger.html#method.new)
    fn default() -> Self {
        BasicLogger::new()
    }
}

impl Log for BasicLogger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        metadata.level() <= Level::Info
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            let level = {
                #[cfg(feature = "colored")]
                match record.level() {
                    Level::Error => format!("[{}]", "-".red()),
                    Level::Info => format!("[{}]", "+".green()),
                    Level::Warn | Level::Debug | Level::Trace => format!("[{}]", "*".yellow()),
                }

                #[cfg(not(feature = "colored"))]
                match record.level() {
                    Level::Error => "[-]",
                    Level::Info => "[+]",
                    Level::Warn | Level::Debug | Level::Trace => "[*]",
                }
            };

            println!("{} {}", level, record.args());
        }
    }

    fn flush(&self) {}
}