diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:19:13 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:19:13 +0000 |
commit | 218caa410aa38c29984be31a5229b9fa717560ee (patch) | |
tree | c54bd55eeb6e4c508940a30e94c0032fbd45d677 /vendor/env_logger/examples/custom_logger.rs | |
parent | Releasing progress-linux version 1.67.1+dfsg1-1~progress7.99u1. (diff) | |
download | rustc-218caa410aa38c29984be31a5229b9fa717560ee.tar.xz rustc-218caa410aa38c29984be31a5229b9fa717560ee.zip |
Merging upstream version 1.68.2+dfsg1.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/env_logger/examples/custom_logger.rs')
-rw-r--r-- | vendor/env_logger/examples/custom_logger.rs | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/vendor/env_logger/examples/custom_logger.rs b/vendor/env_logger/examples/custom_logger.rs new file mode 100644 index 000000000..ca3a4a901 --- /dev/null +++ b/vendor/env_logger/examples/custom_logger.rs @@ -0,0 +1,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`"); +} |