use std::sync::atomic::{AtomicBool, Ordering};
static LOGGING_ENABLED: AtomicBool = AtomicBool::new(true);
pub fn enable_logging() {
LOGGING_ENABLED.store(true, Ordering::SeqCst);
}
pub fn disable_logging() {
LOGGING_ENABLED.store(false, Ordering::SeqCst);
}
pub fn is_logging_enabled() -> bool {
LOGGING_ENABLED.load(Ordering::SeqCst)
}
pub fn log_if_enabled<F>(message: &str, f: F)
where
F: FnOnce() -> String,
{
if is_logging_enabled() {
println!("{}", f());
}
}
pub struct LoggingGuard {
_private: (),
}
impl LoggingGuard {
pub fn new() -> Self {
disable_logging();
Self { _private: () }
}
}
impl Drop for LoggingGuard {
fn drop(&mut self) {
enable_logging();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_logging_toggle() {
let was_enabled = is_logging_enabled();
disable_logging();
assert!(!is_logging_enabled());
enable_logging();
assert!(is_logging_enabled());
if !was_enabled {
disable_logging();
}
}
}