Last active
May 11, 2023 21:50
-
-
Save SpaceMonkeyForever/354fbab6e1ce8a28d40b3e52251708f5 to your computer and use it in GitHub Desktop.
Rust throttled logger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
tracing = "0.1.37" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let mut throttled_logger = ThrottledLogger::new(Duration::from_secs(30)); | |
throttled_info!(throttled_logger, "this will be printed only if the last print was {} secs ago", 30); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::time::{Duration, Instant}; | |
pub struct ThrottledLogger { | |
pub last_log_time: Instant, | |
pub interval: Duration, | |
} | |
impl ThrottledLogger { | |
pub fn new(interval: Duration) -> Self { | |
Self { | |
last_log_time: Instant::now() - interval, | |
interval, | |
} | |
} | |
} | |
#[macro_export] | |
macro_rules! throttled_log { | |
($level:expr, $logger:expr, $($arg:tt)*) => { | |
if $logger.last_log_time.elapsed() >= $logger.interval { | |
tracing::event!($level, $($arg)*); | |
$logger.last_log_time = std::time::Instant::now(); | |
} | |
}; | |
} | |
#[macro_export] | |
macro_rules! throttled_error { | |
($logger:expr, $($arg:tt)*) => { | |
throttled_log!(tracing::Level::ERROR, $logger, $($arg)*); | |
}; | |
} | |
#[macro_export] | |
macro_rules! throttled_warn { | |
($logger:expr, $($arg:tt)*) => { | |
throttled_log!(tracing::Level::WARN, $logger, $($arg)*); | |
}; | |
} | |
#[macro_export] | |
macro_rules! throttled_info { | |
($logger:expr, $($arg:tt)*) => { | |
throttled_log!(tracing::Level::INFO, $logger, $($arg)*); | |
}; | |
} | |
#[macro_export] | |
macro_rules! throttled_debug { | |
($logger:expr, $($arg:tt)*) => { | |
throttled_log!(tracing::Level::DEBUG, $logger, $($arg)*); | |
}; | |
} | |
#[macro_export] | |
macro_rules! throttled_trace { | |
($logger:expr, $($arg:tt)*) => { | |
throttled_log!(tracing::Level::TRACE, $logger, $($arg)*); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment