From 79eae45196e89672a8d564e7595330cd7743fe17 Mon Sep 17 00:00:00 2001 From: Daniel Date: Thu, 9 Apr 2020 13:01:10 +0200 Subject: use log crate instead of own debug! macro This also does away with the scary unsafe{} blocks just to set/get the DEBUG flag. --- src/logger.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/logger.rs (limited to 'src/logger.rs') 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); +} -- cgit v1.2.3