From 6f019fbe8d4debdd0a30c09a06e604f5e4d3a600 Mon Sep 17 00:00:00 2001 From: Istvan Zolyomi Date: Fri, 13 Sep 2024 08:01:48 +0200 Subject: [PATCH] Made Logger reconfiguration Handle accessible without using the init_x() functions, enabling multilog environments. --- src/config/mod.rs | 4 +--- src/lib.rs | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/config/mod.rs b/src/config/mod.rs index d2bd74a6..4ca05489 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -27,9 +27,7 @@ pub use self::raw::{Deserializable, Deserialize, Deserializers, RawConfig}; pub fn init_config(config: runtime::Config) -> Result { let logger = crate::Logger::new(config); log::set_max_level(logger.max_log_level()); - let handle = Handle { - shared: logger.0.clone(), - }; + let handle = logger.handle(); log::set_boxed_logger(Box::new(logger)).map(|()| handle) } diff --git a/src/lib.rs b/src/lib.rs index 0079b623..d22569c8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -414,6 +414,12 @@ impl Logger { pub fn max_log_level(&self) -> LevelFilter { self.0.load().root.max_log_level() } + /// Get a `Handler` instance to reconfigure logger while running + pub fn handle(&self) -> Handle { + Handle { + shared: self.0.clone(), + } + } } impl log::Log for Logger { @@ -462,6 +468,25 @@ impl Handle { log::set_max_level(shared.root.max_log_level()); self.shared.store(Arc::new(shared)); } + + /// Sets the logging configuration with optionally adjusting the global logger settings through the `log`` crate. + /// (log::LOGGER and log::MAX_LOG_LEVEL_FILTER) + pub fn reconfigure(&self, config: Config, mode: EnvMode) { + let shared = SharedLogger::new(config); + match mode { + EnvMode::Single => log::set_max_level(shared.root.max_log_level()), + EnvMode::Multi => {} + }; + self.shared.store(Arc::new(shared)); + } +} + +/// Logger environment mode used for reconfiguration +pub enum EnvMode { + /// Log4rs is the only single logger set as the global logger, e.g. using `init_file`, `init_config` or `log::set_boxed_logger() + Single, + /// Log4rs is working besides other logger(s) and is NOT the global logger + Multi, } #[cfg(test)]