Rate Log
A Rust library for rate-limited logging that prevents spam by tracking message frequency and duration. This crate helps reduce log noise by detecting repeated messages and only outputting warnings when configurable limits are exceeded.
Inspired by the log_hz crate.
Features
- Count-based rate limiting: Limit by number of repeated message occurrences
- Duration-based rate limiting: Limit by accumulated time between repeated messages
- Unified tracking: Always tracks both count and duration for comprehensive reporting
- Smart duration formatting: Automatically formats durations in appropriate units (ms, s, m, h)
- Message deduplication: Automatically resets counters when different messages are logged
- Zero-cost abstractions: Minimal runtime overhead with compile-time optimizations
- Test-friendly: Built-in output capture for unit testing
Quick Start
Add this to your Cargo.toml:
[]
= "0.1.0"
Basic Usage
use ;
use Duration;
// Create a rate limiter that allows up to 5 repeated messages
let mut rate_log = new;
// First occurrence of any message is always printed immediately
rate_log.log; // Prints: "This is a new message"
// Log the same message multiple times - no output until limit exceeded
for i in 0..7
// After 5 repetitions, it will output:
// "Message: \"This is a new message\" repeat for 5 times in the past 10ms"
// Different message gets printed immediately and resets counter
rate_log.log; // Prints: "Different message"
Rate Limiting Types
Count-based Limiting (Limit::Rate)
Tracks the number of times the same message is logged consecutively:
use ;
let mut logger = new;
logger.log; // 1st occurrence - printed immediately: "Error occurred"
logger.log; // 2nd occurrence - counted silently
logger.log; // 3rd occurrence - counted silently
logger.log; // 4th occurrence - triggers warning:
// "Message: \"Error occurred\" repeat for 3 times in the past 15ms"
logger.log; // New message - printed immediately: "Different error"
Duration-based Limiting (Limit::Duration)
Accumulates the time elapsed between consecutive calls with the same message:
use ;
use Duration;
use thread;
let mut logger = new;
logger.log; // 1st occurrence - printed immediately: "Periodic event"
sleep;
logger.log; // 300ms accumulated - silent
sleep;
logger.log; // 1100ms total - triggers warning:
// "Message: \"Periodic event\" repeat for 2 times in the past 1s"
Use Cases
Error Logging
Prevent log spam from repeated error conditions:
use ;
let mut error_logger = new;
// This will only show the first occurrence and then a summary after 10 repetitions
for _ in 0..50
Performance Monitoring
Rate-limit performance warnings:
use ;
use Duration;
let mut perf_logger = new;
// Only warn about slow responses every 30 seconds of accumulated time
if response_time > threshold
Network Logging
Manage connection retry message frequency:
use ;
let mut net_logger = new;
// Limit connection retry spam
while !connected
Behavior
- New message printing: Every new/different message is immediately printed to stdout
- Unified tracking: Always tracks both message count and elapsed duration regardless of limit type
- Silent repetitions: Repeated messages are counted silently until limit exceeded
- Smart duration formatting: Automatically displays duration in appropriate units (ms, s, m, h) with whole numbers
- Comprehensive warnings: Rate limit violations show both count and duration: "Message: "text" repeat for X times in the past Yms"
- Counter reset: Switching to a different message resets all counters and prints the new message
API Documentation
RateLog::new(limit: Limit) -> Self
Creates a new rate limiter with the specified threshold.
RateLog::log(&mut self, msg: &str)
Logs a message with rate limiting applied. New messages are printed immediately, repeated messages are tracked until limits are exceeded.
Limit::Rate(u32)
Count-based rate limiting. Triggers when the same message exceeds the specified count.
Limit::Duration(Duration)
Duration-based rate limiting. Triggers when accumulated time between repeated messages exceeds the specified duration.
Testing
Run the test suite:
Run with output to see the rate limiting in action:
Todo
- Add configurable output formatting
- Support for custom output writers (not just stdout)
- Add reset methods for manual counter clearing
- Benchmarks and performance optimization
-
no_stdsupport for embedded environments - Integration with popular logging frameworks (
log,tracing) - Configurable timestamp precision
- Memory usage optimization for long-running applications
- Async support for non-blocking rate limiting
- Multi-threaded safety with
Arc<Mutex<RateLog>> - Persistent rate limiting across application restarts
- Rate limiting policies (exponential backoff, sliding window)
- Metrics integration (Prometheus, StatsD)
Development
# Clone the repository
# Run tests
# Run tests with output
# Check documentation
# Run clippy for linting
# Format code
License
This project is licensed under the MIT license (LICENSE or http://opensource.org/licenses/MIT).
Contribution
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to:
- Update tests as appropriate
- Follow the existing code style
- Run
cargo fmtandcargo clippybefore submitting - Add documentation for new features