log_limit 0.2.4

A rate limiting logging crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
#![doc = include_str!("../README.md")]

use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::LazyLock;
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;

#[cfg(test)]
mod testing_logger;

#[doc(hidden)]
pub struct RateLimiter {
    count: usize,
    timestamp: Instant,
    logged_timeout: bool,
}

impl Default for RateLimiter {
    fn default() -> Self {
        Self::new()
    }
}

impl RateLimiter {
    pub fn new() -> Self {
        Self {
            count: 0,
            timestamp: Instant::now(),
            logged_timeout: false,
        }
    }

    pub fn log_maybe(&mut self, period: Duration, max_per_time: usize, log: impl Fn()) {
        let now = Instant::now();

        #[cfg(feature = "warning-messages")]
        let calculated_duration = now.duration_since(self.timestamp);
        if self.count < max_per_time {
            log();
            self.count += 1;

            #[cfg(feature = "warning-messages")]
            if self.count == max_per_time && period >= calculated_duration {
                log::warn!(
                    "Hit logging threshold! Starting to ignore the previous log for {:.2?}",
                    period - calculated_duration
                );
                self.logged_timeout = true;
            }
        } else {
            let calculated_duration = now.duration_since(self.timestamp);
            if calculated_duration > period {
                #[cfg(feature = "warning-messages")]
                let filtered_log_count = self.count - max_per_time;
                #[cfg(feature = "warning-messages")]
                if self.logged_timeout {
                    log::warn!(
                        "Ignored {filtered_log_count} logs since {:.2?} ago. Starting to log again...",
                        calculated_duration
                    );
                }
                self.logged_timeout = false;
                log();
                self.count = 1;
                self.timestamp = now;
            } else {
                self.count += 1;
            }
        }
    }
}

#[doc(hidden)]
pub struct SynchronisedRateLimiter {
    count: AtomicUsize,
    timestamp: Mutex<Instant>,
}

impl SynchronisedRateLimiter {
    pub const fn new() -> LazyLock<Self> {
        LazyLock::new(|| Self {
            count: AtomicUsize::new(0),
            timestamp: Instant::now().into(),
        })
    }

    pub fn log_maybe(&self, period: Duration, max_per_time: usize, log: impl Fn()) {
        let count = self.count.fetch_add(1, Ordering::Relaxed) + 1;
        if count <= max_per_time {
            log();
            #[cfg(feature = "warning-messages")]
            if count == max_per_time {
                log::warn!(
                    "Hit logging threshold! Starting to ignore the previous log for less than {:.2?}",
                    period
                );
            }
        } else {
            let now = Instant::now();
            let mut timestamp = self.timestamp.lock().unwrap();

            let calculated_duration = now.duration_since(*timestamp);
            if calculated_duration > period {
                #[cfg(feature = "warning-messages")]
                let filtered_log_count = self.count.swap(1, Ordering::Relaxed) - max_per_time - 1;
                #[cfg(not(feature = "warning-messages"))]
                let _filtered_log_count = self.count.swap(1, Ordering::Relaxed) - max_per_time - 1;
                #[cfg(feature = "warning-messages")]
                log::warn!(
                    "Ignored {filtered_log_count} logs since {:.2?} ago. Starting to log again...",
                    calculated_duration
                );
                log();
                *timestamp = now;
            }
        }
    }
}

// Helper macro to reduce duplication in global limit macros
#[doc(hidden)]
#[macro_export]
macro_rules! global_limit_impl {
    ($level:expr, $max_per_time:expr, $period:expr, target: $target:expr, $($arg:tt)+) => {{
        use $crate::SynchronisedRateLimiter;
        use std::sync::LazyLock;
        if log::log_enabled!($level) {
            static RATE_LIMITER: LazyLock<SynchronisedRateLimiter> = SynchronisedRateLimiter::new();
            RATE_LIMITER.log_maybe($period, $max_per_time, || log::log!(target: $target, $level, $($arg)+));
        }
    }};
    ($level:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {{
        use $crate::SynchronisedRateLimiter;
        use std::sync::LazyLock;
        if log::log_enabled!($level) {
            static RATE_LIMITER: LazyLock<SynchronisedRateLimiter> = SynchronisedRateLimiter::new();
            RATE_LIMITER.log_maybe($period, $max_per_time, || log::log!($level, $($arg)+));
        }
    }};
}

#[macro_export]
macro_rules! error_limit_global {
    (target: $target:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::global_limit_impl!(log::Level::Error, $max_per_time, $period, target: $target, $($arg)+)
    };
    ($max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::global_limit_impl!(log::Level::Error, $max_per_time, $period, $($arg)+)
    };
}

#[macro_export]
macro_rules! warn_limit_global {
    (target: $target:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::global_limit_impl!(log::Level::Warn, $max_per_time, $period, target: $target, $($arg)+)
    };
    ($max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::global_limit_impl!(log::Level::Warn, $max_per_time, $period, $($arg)+)
    };
}

#[macro_export]
macro_rules! info_limit_global {
    (target: $target:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::global_limit_impl!(log::Level::Info, $max_per_time, $period, target: $target, $($arg)+)
    };
    ($max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::global_limit_impl!(log::Level::Info, $max_per_time, $period, $($arg)+)
    };
}

#[macro_export]
macro_rules! debug_limit_global {
    (target: $target:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::global_limit_impl!(log::Level::Debug, $max_per_time, $period, target: $target, $($arg)+)
    };
    ($max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::global_limit_impl!(log::Level::Debug, $max_per_time, $period, $($arg)+)
    };
}

#[macro_export]
macro_rules! trace_limit_global {
    (target: $target:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::global_limit_impl!(log::Level::Trace, $max_per_time, $period, target: $target, $($arg)+)
    };
    ($max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::global_limit_impl!(log::Level::Trace, $max_per_time, $period, $($arg)+)
    };
}

// Helper macro to reduce duplication in thread-local limit macros
#[doc(hidden)]
#[macro_export]
macro_rules! limit_impl {
    ($level:expr, $max_per_time:expr, $period:expr, target: $target:expr, $($arg:tt)+) => {{
        use $crate::RateLimiter;
        use std::cell::RefCell;
        use std::thread_local;

        if log::log_enabled!($level) {
            thread_local! {
                static RATE_LIMITER: RefCell<RateLimiter> = RefCell::new(RateLimiter::new());
            }

            RATE_LIMITER.with(|rate_limiter| {
                rate_limiter
                    .borrow_mut()
                    .log_maybe($period, $max_per_time, || log::log!(target: $target, $level, $($arg)+))
            });
        }
    }};
    ($level:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {{
        use $crate::RateLimiter;
        use std::cell::RefCell;
        use std::thread_local;

        if log::log_enabled!($level) {
            thread_local! {
                static RATE_LIMITER: RefCell<RateLimiter> = RefCell::new(RateLimiter::new());
            }

            RATE_LIMITER.with(|rate_limiter| {
                rate_limiter
                    .borrow_mut()
                    .log_maybe($period, $max_per_time, || log::log!($level, $($arg)+))
            });
        }
    }};
}

#[macro_export]
macro_rules! error_limit {
    (target: $target:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::limit_impl!(log::Level::Error, $max_per_time, $period, target: $target, $($arg)+)
    };
    ($max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::limit_impl!(log::Level::Error, $max_per_time, $period, $($arg)+)
    };
}

#[macro_export]
macro_rules! warn_limit {
    (target: $target:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::limit_impl!(log::Level::Warn, $max_per_time, $period, target: $target, $($arg)+)
    };
    ($max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::limit_impl!(log::Level::Warn, $max_per_time, $period, $($arg)+)
    };
}

#[macro_export]
macro_rules! info_limit {
    (target: $target:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::limit_impl!(log::Level::Info, $max_per_time, $period, target: $target, $($arg)+)
    };
    ($max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::limit_impl!(log::Level::Info, $max_per_time, $period, $($arg)+)
    };
}

#[macro_export]
macro_rules! debug_limit {
    (target: $target:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::limit_impl!(log::Level::Debug, $max_per_time, $period, target: $target, $($arg)+)
    };
    ($max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::limit_impl!(log::Level::Debug, $max_per_time, $period, $($arg)+)
    };
}

#[macro_export]
macro_rules! trace_limit {
    (target: $target:expr, $max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::limit_impl!(log::Level::Trace, $max_per_time, $period, target: $target, $($arg)+)
    };
    ($max_per_time:expr, $period:expr, $($arg:tt)+) => {
        $crate::limit_impl!(log::Level::Trace, $max_per_time, $period, $($arg)+)
    };
}

#[cfg(test)]
mod tests {
    use std::thread;
    use std::time::Duration;
    use std::time::Instant;

    enum LoggerVariant {
        TheadLocal,
        Shared,
    }

    fn logger_limits_correctly(variant_under_test: LoggerVariant) {
        crate::testing_logger::setup();
        for _ in 0..11 {
            match variant_under_test {
                LoggerVariant::TheadLocal => {
                    info_limit!(2, Duration::from_millis(50), "Logging on repeat")
                }
                LoggerVariant::Shared => {
                    info_limit_global!(2, Duration::from_millis(50), "Logging on repeat")
                }
            }
            thread::sleep(Duration::from_millis(11));
            // 00: Log
            // 11: Log (and warn of omission)
            // 22: Omit
            // 33: Omit
            // 44: Omit
            // 55: Log (and warn: missed 3)
            // 66: Log (and warn of omission)
            // 77: Omit
            // 88: Omit
            // 99: Omit
            // 110: Log (and warn: missed 3)
        }
        crate::testing_logger::validate(|captured_logs| {
            #[cfg(feature = "warning-messages")]
            let warning_logs = captured_logs
                .iter()
                .filter(|log| log.level == log::Level::Warn);

            let info_logs = captured_logs
                .iter()
                .filter(|log| log.level == log::Level::Info);

            #[cfg(feature = "warning-messages")]
            assert_eq!(warning_logs.clone().count(), 4);
            assert_eq!(info_logs.count(), 5);
            #[cfg(feature = "warning-messages")]
            {
                let ignored_warnings: Vec<_> = warning_logs
                    .filter(|log| log.body.contains("Ignored"))
                    .collect();
                assert_eq!(ignored_warnings.len(), 2);
                assert_eq!(
                    "3",
                    ignored_warnings[0].body.split_whitespace().nth(1).unwrap()
                );
                assert_eq!(
                    "3",
                    ignored_warnings[1].body.split_whitespace().nth(1).unwrap()
                );
            }
        })
    }

    #[test]
    fn thread_local_logger_limits_correctly() {
        logger_limits_correctly(LoggerVariant::TheadLocal);
    }

    #[test]
    fn shared_logger_limits_correctly() {
        logger_limits_correctly(LoggerVariant::Shared);
    }

    const ACCEPTABLE_DROP_FACTOR: f64 = 0.99;
    const TEST_TIME_MS: usize = 500;
    const TEST_PERIOD_MS: usize = 1;
    const MAX_LOGS_PER_PERIOD: usize = 500;
    #[cfg(feature = "warning-messages")]
    const MAX_EXPECTED_WARNING_LOGS_PER_PERIOD: usize = 2;
    fn spamming_does_not_work(spam_logs: impl Fn()) {
        crate::testing_logger::setup();
        spam_logs();
        crate::testing_logger::validate(|captured_logs| {
            #[cfg(feature = "warning-messages")]
            let warning_logs = captured_logs
                .iter()
                .filter(|log| log.level == log::Level::Warn);

            let info_logs = captured_logs
                .iter()
                .filter(|log| log.level == log::Level::Info);

            #[cfg(feature = "warning-messages")]
            let warning_logs_count = warning_logs.count();
            let info_logs_count = info_logs.count();

            // Ensure we don't overstep the limit on average
            #[cfg(feature = "warning-messages")]
            assert!(
                warning_logs_count
                    <= TEST_TIME_MS / TEST_PERIOD_MS * MAX_EXPECTED_WARNING_LOGS_PER_PERIOD
            );
            assert!(info_logs_count <= MAX_LOGS_PER_PERIOD * TEST_TIME_MS);

            #[cfg(feature = "warning-messages")]
            assert!(
                warning_logs_count as f64
                    > ((TEST_TIME_MS / TEST_PERIOD_MS * MAX_EXPECTED_WARNING_LOGS_PER_PERIOD)
                        as f64
                        * ACCEPTABLE_DROP_FACTOR)
            );
            assert!(
                info_logs_count as f64
                    > ((MAX_LOGS_PER_PERIOD * TEST_TIME_MS) as f64 * ACCEPTABLE_DROP_FACTOR)
            );
        })
    }

    #[test]
    fn thread_local_spamming_does_not_work() {
        spamming_does_not_work(|| {
            let start = Instant::now();
            while Instant::now().duration_since(start) < Duration::from_millis(TEST_TIME_MS as u64)
            {
                info_limit!(
                    MAX_LOGS_PER_PERIOD,
                    Duration::from_millis(TEST_PERIOD_MS as u64),
                    "Logging on repeat"
                );
            }
        })
    }

    #[test]
    fn sync_spamming_does_not_work() {
        spamming_does_not_work(|| {
            let start = Box::new(Instant::now());
            let start = Box::leak(start);
            let handles: Vec<_> = (0..1)
                .map(|_| {
                    std::thread::spawn(|| {
                        while Instant::now().duration_since(*start)
                            < Duration::from_millis(TEST_TIME_MS as u64)
                        {
                            info_limit_global!(
                                MAX_LOGS_PER_PERIOD,
                                Duration::from_millis(TEST_PERIOD_MS as u64),
                                "Logging on repeat"
                            );
                        }
                    })
                })
                .collect();
            for handle in handles {
                handle.join().unwrap();
            }
        })
    }

    #[test]
    fn all_synchronised_variants_compile() {
        error_limit_global!(1, Duration::from_millis(1), "");
        warn_limit_global!(1, Duration::from_millis(1), "");
        info_limit_global!(1, Duration::from_millis(1), "");
        debug_limit_global!(1, Duration::from_millis(1), "");
        trace_limit_global!(1, Duration::from_millis(1), "");
    }

    #[test]
    fn all_thread_variants_compile() {
        error_limit!(1, Duration::from_millis(1), "");
        warn_limit!(1, Duration::from_millis(1), "");
        info_limit!(1, Duration::from_millis(1), "");
        debug_limit!(1, Duration::from_millis(1), "");
        trace_limit!(1, Duration::from_millis(1), "");
    }

    #[test]
    fn target_parameter_works() {
        error_limit!(target: "custom_target", 1, Duration::from_millis(1), "");
        warn_limit!(target: "custom_target", 1, Duration::from_millis(1), "");
        info_limit!(target: "custom_target", 1, Duration::from_millis(1), "");
        debug_limit!(target: "custom_target", 1, Duration::from_millis(1), "");
        trace_limit!(target: "custom_target", 1, Duration::from_millis(1), "");

        error_limit_global!(target: "custom_target", 1, Duration::from_millis(1), "");
        warn_limit_global!(target: "custom_target", 1, Duration::from_millis(1), "");
        info_limit_global!(target: "custom_target", 1, Duration::from_millis(1), "");
        debug_limit_global!(target: "custom_target", 1, Duration::from_millis(1), "");
        trace_limit_global!(target: "custom_target", 1, Duration::from_millis(1), "");
    }

    #[test]
    fn max_per_time_longer_than_period_overflow() {
        crate::testing_logger::setup();
        fn log_function() {
            info_limit!(3, Duration::from_millis(10), "");
        }

        // Trigger threshold
        log_function();
        log_function();
        log_function();
        log_function();

        // Reset after period was reached and record timestamp
        thread::sleep(Duration::from_millis(11));
        log_function();

        // Get to just one log before hitting the threshold

        // Ensure time delta is longer than period
        thread::sleep(Duration::from_millis(11));
        log_function();
        log_function();
    }

    #[test]
    fn thread_local_suppressed_levels_are_ignored() {
        crate::testing_logger::setup();

        // Restrict logging to Warn and above
        log::set_max_level(log::LevelFilter::Warn);

        for _ in 0..10 {
            debug_limit!(
                2,
                Duration::from_secs(1),
                "This debug message is suppressed"
            );
        }

        crate::testing_logger::validate(|captured_logs| {
            assert_eq!(captured_logs.len(), 0,);
        });
    }

    #[test]
    fn global_suppressed_levels_are_ignored() {
        crate::testing_logger::setup();

        // Restrict logging to Warn and above
        log::set_max_level(log::LevelFilter::Warn);

        for _ in 0..10 {
            debug_limit_global!(
                2,
                Duration::from_secs(1),
                "This global debug message is suppressed"
            );
        }

        crate::testing_logger::validate(|captured_logs| {
            assert_eq!(captured_logs.len(), 0,);
        });
    }
}