Overview
SamplingWriter wraps an io.Writer with rate limiting to prevent log flooding. It allows a maximum number of messages per time interval, dropping excess messages.
This is useful for high-volume logs where you want to prevent disk I/O or network overload while still capturing representative samples.
Type Definitions
Sampler
Controls the rate of log messages.SamplingWriter
Writes to an underlying writer with sampling.Sampler Constructor
NewSampler
Creates a new Sampler with threshold and interval.threshold- Maximum number of messages per intervalinterval- Time window for counting
*Sampler- Configured sampler
SamplingWriter Constructors
NewSamplingWriter
Creates a writer with sampling.writer- Underlying writer to wrapthreshold- Maximum messages per intervalinterval- Time window for counting
*SamplingWriter- Rate-limited writer
NewSamplingWriterWithCallback
Creates a writer with sampling and drop notification.writer- Underlying writer to wrapthreshold- Maximum messages per intervalinterval- Time window for countingonDrop- Function called when messages are dropped
*SamplingWriter- Rate-limited writer with callback
Sampler Methods
Allow
Returns true if the message should be logged.bool- true if within rate limit, false if should be dropped
- Resets counter if interval has passed
- Increments counter if below threshold
- Returns false if threshold exceeded
AllowN
Allows N messages and returns how many were allowed.n- Number of messages to allow
int- Number of messages allowed (0 to n)
GetCount
Returns the current count in the interval.int- Current message count
GetThreshold
Returns the configured threshold.int- Maximum messages per interval
Reset
Resets the counter immediately.- Manual reset for testing
- Policy changes
SamplingWriter Methods
Write
Implements io.Writer with sampling.p- Bytes to write
n- Always len(p) (even if dropped)err- Always nil (unless underlying writer fails)
- Checks sampler.Allow()
- If allowed, writes to underlying writer
- If not allowed, calls onDrop callback and returns success
- Always returns len(p) to prevent logger errors
Close
Closes the underlying writer if it implements io.Closer.error- Error from underlying Close, or nil
Usage Examples
Basic Rate Limiting
With Drop Monitoring
High-Volume Debug Logs
Different Rates for Different Levels
Burst Protection
Metrics Collection
Testing Sampling Behavior
Best Practices
Performance
SamplingWriter adds minimal overhead: Sampler.Allow():- Time check: ~20ns
- Mutex lock: ~20ns
- Counter increment: ~1ns
- Total: ~41ns per call
- Allowed: ~41ns + underlying writer time
- Dropped: ~41ns (no write)
Thread Safety
All methods are thread-safe:sync.Mutex to protect counter state.
Related
- RotatingFileWriter - File rotation writer
- MultiWriter - Multiple destination writer
- Logger Options - WithOutput option