aboutsummaryrefslogtreecommitdiff
path: root/src/logger.rs
blob: f47d19e960eadfee3d9a69a212bc19a193bdbebe (plain)
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
use log::{Level, LevelFilter, Metadata, Record};

struct StderrLogger(LevelFilter);

impl log::Log for StderrLogger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        metadata.level() <= self.0
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            eprintln!("{} - {}", record.level(), record.args());
        }
    }

    fn flush(&self) {}
}

/// Initializes the logging with the desired level.
///
/// Note that this should only be called once per program start.
///
/// The given level is the maximum level that you want to output. Messages higher than that will be
/// discarded.
pub fn initialize(max_level: Level) {
    let filter = max_level.to_level_filter();
    let logger = Box::new(StderrLogger(filter));
    log::set_boxed_logger(logger).expect("Failed to set logger");
    log::set_max_level(filter);
}