diff options
Diffstat (limited to 'src/logger.rs')
-rw-r--r-- | src/logger.rs | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/src/logger.rs b/src/logger.rs new file mode 100644 index 0000000..f47d19e --- /dev/null +++ b/src/logger.rs @@ -0,0 +1,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); +} |