Skip to content

Commit

Permalink
Made Logger reconfiguration Handle accessible without using the init_…
Browse files Browse the repository at this point in the history
…x() functions, enabling multilog environments.
  • Loading branch information
Istvan Zolyomi committed Sep 13, 2024
1 parent 1a758c1 commit 6f019fb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
4 changes: 1 addition & 3 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ pub use self::raw::{Deserializable, Deserialize, Deserializers, RawConfig};
pub fn init_config(config: runtime::Config) -> Result<crate::Handle, SetLoggerError> {
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)
}

Expand Down
25 changes: 25 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)]
Expand Down

0 comments on commit 6f019fb

Please sign in to comment.