basic_logger/
lib.rs

1//! A basic logger for the log facade.
2//!
3//! Usage
4//!
5//! 1. Add the required dependencies to your `Cargo.toml`.
6//! ```toml
7//! [dependencies]
8//! basic-logger = "0.1"
9//! log = "0.4"
10//! ```
11//!
12//! _Note:_ Coloured output will be enabled by default. You can remove this feature by disabling all features.
13//! ```toml
14//! [dependencies]
15//! ...
16//! basic-logger = { version = "0.1", default-features = false }
17//! ```
18//!
19//! 2. Initialize the logger _(Do this as early as possible in your project)_.
20//! ```rust
21//! use basic_logger::BasicLogger;
22//!
23//! use log::info;
24//!
25//! fn main() {
26//!     BasicLogger::new().init().unwrap();
27//!
28//!     info!("Hello, world!");
29//! }
30//! ```
31
32#[cfg(feature = "colored")]
33use colored::Colorize;
34
35use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
36
37/// Implements [`log`] and a set of builder methods used for configuration.
38///
39/// Use the builder methods on this struct to configure the logger, then call [`init`] to initialize the actual logger.
40pub struct BasicLogger {
41    default_filter: LevelFilter,
42}
43
44impl BasicLogger {
45    /// Initialize the logger with the default log level set to `Level::Trace`.
46    pub fn new() -> Self {
47        Self {
48            default_filter: LevelFilter::Trace,
49        }
50    }
51
52    /// Set the default log level.
53    #[must_use = "You must call init() to begin logging"]
54    pub fn with_level(mut self, level: LevelFilter) -> Self {
55        self.default_filter = level;
56
57        self
58    }
59
60    /// Initialize the actual logger.
61    pub fn init(self) -> Result<(), SetLoggerError> {
62        log::set_max_level(self.default_filter);
63        log::set_boxed_logger(Box::new(self))?;
64
65        Ok(())
66    }
67}
68
69impl Default for BasicLogger {
70    /// See [this](struct.BasicLogger.html#method.new)
71    fn default() -> Self {
72        BasicLogger::new()
73    }
74}
75
76impl Log for BasicLogger {
77    fn enabled(&self, metadata: &Metadata) -> bool {
78        metadata.level() <= Level::Info
79    }
80
81    fn log(&self, record: &Record) {
82        if self.enabled(record.metadata()) {
83            let level = {
84                #[cfg(feature = "colored")]
85                match record.level() {
86                    Level::Error => format!("[{}]", "-".red()),
87                    Level::Info => format!("[{}]", "+".green()),
88                    Level::Warn | Level::Debug | Level::Trace => format!("[{}]", "*".yellow()),
89                }
90
91                #[cfg(not(feature = "colored"))]
92                match record.level() {
93                    Level::Error => "[-]",
94                    Level::Info => "[+]",
95                    Level::Warn | Level::Debug | Level::Trace => "[*]",
96                }
97            };
98
99            println!("{} {}", level, record.args());
100        }
101    }
102
103    fn flush(&self) {}
104}