Skip to content

Commit 3ffe420

Browse files
committed
Implement log_every_n macro
Add the log_every_n macro that will log an event after every n steps. Fixes issue #3457
1 parent efc690f commit 3ffe420

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

tracing/src/macros.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2701,6 +2701,48 @@ macro_rules! error {
27012701
);
27022702
}
27032703

2704+
/// Constructs an event after every n times.
2705+
///
2706+
/// This functions similarly to the [`event!`] macro. See [the top-level
2707+
/// documentation][lib] for details on the syntax accepted by
2708+
/// this macro.
2709+
///
2710+
/// [`event!`]: crate::event!
2711+
/// [lib]: crate#using-the-macros
2712+
///
2713+
/// # Examples
2714+
///
2715+
/// ```rust
2716+
/// use tracing::warn;
2717+
/// use tracing::log_every_n;
2718+
///
2719+
/// # fn main() {
2720+
///
2721+
/// let warn_description = "Invalid Input";
2722+
/// let input = &[0x27, 0x45];
2723+
///
2724+
/// log_every_n!(3, warn!(?input, warning = warn_description));
2725+
/// log_every_n!(3, warn!(
2726+
/// target: "input_events",
2727+
/// warning = warn_description,
2728+
/// "Received warning for input: {:?}", input,
2729+
/// ));
2730+
/// log_every_n!(3, warn!(name: "invalid", ?input));
2731+
/// # }
2732+
/// ```
2733+
#[macro_export]
2734+
macro_rules! log_every_n {
2735+
($n:expr, $($log:tt)*) => {
2736+
{
2737+
static __COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2738+
let val = __COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2739+
if val % $n == 0 {
2740+
$($log)*
2741+
}
2742+
}
2743+
};
2744+
}
2745+
27042746
/// Constructs a new static callsite for a span or event.
27052747
#[doc(hidden)]
27062748
#[macro_export]

0 commit comments

Comments
 (0)