summaryrefslogtreecommitdiffstats
path: root/third_party/rust/env_logger/examples/custom_logger.rs
blob: ca3a4a90120a1b52fa00b7faa561354d3cc069e4 (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
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
/*!
Using `env_logger` to drive a custom logger.

Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`:

```no_run,shell
$ export MY_LOG_LEVEL='info'
```

If you only want to change the way logs are formatted, look at the `custom_format` example.
*/

#[macro_use]
extern crate log;

use env_logger::filter::{Builder, Filter};

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

const FILTER_ENV: &str = "MY_LOG_LEVEL";

struct MyLogger {
    inner: Filter,
}

impl MyLogger {
    fn new() -> MyLogger {
        let mut builder = Builder::from_env(FILTER_ENV);

        MyLogger {
            inner: builder.build(),
        }
    }

    fn init() -> Result<(), SetLoggerError> {
        let logger = Self::new();

        log::set_max_level(logger.inner.filter());
        log::set_boxed_logger(Box::new(logger))
    }
}

impl Log for MyLogger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        self.inner.enabled(metadata)
    }

    fn log(&self, record: &Record) {
        // Check if the record is matched by the logger before logging
        if self.inner.matches(record) {
            println!("{} - {}", record.level(), record.args());
        }
    }

    fn flush(&self) {}
}

fn main() {
    MyLogger::init().unwrap();

    info!("a log from `MyLogger`");
}