• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*!
2 Using `env_logger` to drive a custom logger.
3 
4 Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`:
5 
6 ```no_run,shell
7 $ export MY_LOG_LEVEL='info'
8 ```
9 
10 If you only want to change the way logs are formatted, look at the `custom_format` example.
11 */
12 
13 #[macro_use]
14 extern crate log;
15 
16 use env_logger::filter::{Builder, Filter};
17 
18 use log::{Log, Metadata, Record, SetLoggerError};
19 
20 const FILTER_ENV: &str = "MY_LOG_LEVEL";
21 
22 struct MyLogger {
23     inner: Filter,
24 }
25 
26 impl MyLogger {
new() -> MyLogger27     fn new() -> MyLogger {
28         let mut builder = Builder::from_env(FILTER_ENV);
29 
30         MyLogger {
31             inner: builder.build(),
32         }
33     }
34 
init() -> Result<(), SetLoggerError>35     fn init() -> Result<(), SetLoggerError> {
36         let logger = Self::new();
37 
38         log::set_max_level(logger.inner.filter());
39         log::set_boxed_logger(Box::new(logger))
40     }
41 }
42 
43 impl Log for MyLogger {
enabled(&self, metadata: &Metadata) -> bool44     fn enabled(&self, metadata: &Metadata) -> bool {
45         self.inner.enabled(metadata)
46     }
47 
log(&self, record: &Record)48     fn log(&self, record: &Record) {
49         // Check if the record is matched by the logger before logging
50         if self.inner.matches(record) {
51             println!("{} - {}", record.level(), record.args());
52         }
53     }
54 
flush(&self)55     fn flush(&self) {}
56 }
57 
main()58 fn main() {
59     MyLogger::init().unwrap();
60 
61     info!("a log from `MyLogger`");
62 }
63