Skip to content

Instantly share code, notes, and snippets.

@SpaceMonkeyForever
Last active May 11, 2023 21:50
Show Gist options
  • Save SpaceMonkeyForever/354fbab6e1ce8a28d40b3e52251708f5 to your computer and use it in GitHub Desktop.
Save SpaceMonkeyForever/354fbab6e1ce8a28d40b3e52251708f5 to your computer and use it in GitHub Desktop.
Rust throttled logger
tracing = "0.1.37"
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);
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