-
Notifications
You must be signed in to change notification settings - Fork 75
Add a rate limit on logger #352
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| package log | ||
|
|
||
| import ( | ||
| "github.com/prometheus/client_golang/prometheus" | ||
| "github.com/prometheus/client_golang/prometheus/promauto" | ||
| "golang.org/x/time/rate" | ||
| ) | ||
|
|
||
| const ( | ||
| infoLevel = "info" | ||
| debugLevel = "debug" | ||
| warnLevel = "warning" | ||
| errorLevel = "error" | ||
| ) | ||
|
|
||
| type RateLimitedLogger struct { | ||
| next Interface | ||
| limiter *rate.Limiter | ||
|
|
||
| discardedLogLinesCounter *prometheus.CounterVec | ||
| } | ||
|
|
||
| // NewRateLimitedLogger returns a logger.Interface that is limited to the given number of logs per second, | ||
| // with the given burst size. | ||
| func NewRateLimitedLogger(logger Interface, logsPerSecond rate.Limit, burstSize int, reg prometheus.Registerer) Interface { | ||
| discardedLogLinesCounter := promauto.With(reg).NewCounterVec(prometheus.CounterOpts{ | ||
| Name: "rate_limit_logger_discarded_log_lines_total", | ||
| Help: "Total number of discarded log lines per level.", | ||
| }, []string{"level"}) | ||
|
|
||
| return &RateLimitedLogger{ | ||
| next: logger, | ||
| limiter: rate.NewLimiter(logsPerSecond, burstSize), | ||
| discardedLogLinesCounter: discardedLogLinesCounter, | ||
| } | ||
| } | ||
|
|
||
| func (l *RateLimitedLogger) Debugf(format string, args ...interface{}) { | ||
| if l.limiter.Allow() { | ||
| l.next.Debugf(format, args...) | ||
| } else { | ||
| l.discardedLogLinesCounter.WithLabelValues(debugLevel).Inc() | ||
duricanikolic marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| func (l *RateLimitedLogger) Debugln(args ...interface{}) { | ||
| if l.limiter.Allow() { | ||
| l.next.Debugln(args...) | ||
| } else { | ||
| l.discardedLogLinesCounter.WithLabelValues(debugLevel).Inc() | ||
| } | ||
| } | ||
|
|
||
| func (l *RateLimitedLogger) Infof(format string, args ...interface{}) { | ||
| if l.limiter.Allow() { | ||
| l.next.Infof(format, args...) | ||
| } else { | ||
| l.discardedLogLinesCounter.WithLabelValues(infoLevel).Inc() | ||
| } | ||
| } | ||
|
|
||
| func (l *RateLimitedLogger) Infoln(args ...interface{}) { | ||
| if l.limiter.Allow() { | ||
| l.next.Infoln(args...) | ||
| } else { | ||
| l.discardedLogLinesCounter.WithLabelValues(infoLevel).Inc() | ||
| } | ||
| } | ||
|
|
||
| func (l *RateLimitedLogger) Errorf(format string, args ...interface{}) { | ||
| if l.limiter.Allow() { | ||
| l.next.Errorf(format, args...) | ||
| } else { | ||
| l.discardedLogLinesCounter.WithLabelValues(errorLevel).Inc() | ||
| } | ||
| } | ||
|
|
||
| func (l *RateLimitedLogger) Errorln(args ...interface{}) { | ||
| if l.limiter.Allow() { | ||
| l.next.Errorln(args...) | ||
| } else { | ||
| l.discardedLogLinesCounter.WithLabelValues(errorLevel).Inc() | ||
| } | ||
| } | ||
|
|
||
| func (l *RateLimitedLogger) Warnf(format string, args ...interface{}) { | ||
| if l.limiter.Allow() { | ||
| l.next.Warnf(format, args...) | ||
| } else { | ||
| l.discardedLogLinesCounter.WithLabelValues(warnLevel).Inc() | ||
| } | ||
| } | ||
|
|
||
| func (l *RateLimitedLogger) Warnln(args ...interface{}) { | ||
| if l.limiter.Allow() { | ||
| l.next.Warnln(args...) | ||
| } else { | ||
| l.discardedLogLinesCounter.WithLabelValues(warnLevel).Inc() | ||
| } | ||
| } | ||
|
|
||
| func (l *RateLimitedLogger) WithField(key string, value interface{}) Interface { | ||
| return &RateLimitedLogger{ | ||
| next: l.next.WithField(key, value), | ||
| limiter: l.limiter, | ||
| discardedLogLinesCounter: l.discardedLogLinesCounter, | ||
| } | ||
| } | ||
|
|
||
| func (l *RateLimitedLogger) WithFields(f Fields) Interface { | ||
| return &RateLimitedLogger{ | ||
| next: l.next.WithFields(f), | ||
| limiter: l.limiter, | ||
| discardedLogLinesCounter: l.discardedLogLinesCounter, | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| package log | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "strings" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus" | ||
| "github.com/prometheus/client_golang/prometheus/testutil" | ||
| "github.com/sirupsen/logrus" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestRateLimitedLoggerLogs(t *testing.T) { | ||
| buf := bytes.NewBuffer(nil) | ||
| c := newCounterLogger(buf) | ||
| reg := prometheus.NewPedanticRegistry() | ||
| r := NewRateLimitedLogger(c, 1, 1, reg) | ||
|
|
||
| r.Errorln("Error will be logged") | ||
| assert.Equal(t, 1, c.count) | ||
|
|
||
| logContains := []string{"error", "Error will be logged"} | ||
| c.verify(t, logContains) | ||
| } | ||
|
|
||
| func TestRateLimitedLoggerLimits(t *testing.T) { | ||
| buf := bytes.NewBuffer(nil) | ||
| c := newCounterLogger(buf) | ||
| reg := prometheus.NewPedanticRegistry() | ||
| r := NewRateLimitedLogger(c, 2, 2, reg) | ||
|
|
||
| r.Errorln("error 1 will be logged") | ||
| assert.Equal(t, 1, c.count) | ||
| c.verify(t, []string{"error", "error 1 will be logged"}) | ||
|
|
||
| r.Infoln("info 1 will be logged") | ||
| assert.Equal(t, 2, c.count) | ||
| c.verify(t, []string{"info", "info 1 will be logged"}) | ||
|
|
||
| r.Debugln("debug 1 will be discarded") | ||
| assert.Equal(t, 2, c.count) | ||
duricanikolic marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| r.Warnln("warning 1 will be discarded") | ||
| assert.Equal(t, 2, c.count) | ||
|
|
||
| require.NoError(t, testutil.GatherAndCompare(reg, strings.NewReader(` | ||
| # HELP rate_limit_logger_discarded_log_lines_total Total number of discarded log lines per level. | ||
| # TYPE rate_limit_logger_discarded_log_lines_total counter | ||
| rate_limit_logger_discarded_log_lines_total{level="debug"} 1 | ||
| rate_limit_logger_discarded_log_lines_total{level="warning"} 1 | ||
| `))) | ||
|
|
||
| // we wait 1 second, so the next group of lines can be logged | ||
| time.Sleep(time.Second) | ||
| r.Debugln("debug 2 will be logged") | ||
| assert.Equal(t, 3, c.count) | ||
| c.verify(t, []string{"debug", "debug 2 will be logged"}) | ||
|
|
||
| r.Infoln("info 2 will be logged") | ||
| assert.Equal(t, 4, c.count) | ||
| c.verify(t, []string{"info", "info 2 will be logged"}) | ||
|
|
||
| r.Errorln("error 2 will be discarded") | ||
| assert.Equal(t, 4, c.count) | ||
|
|
||
| r.Warnln("warning 2 will be discarded") | ||
| assert.Equal(t, 4, c.count) | ||
|
|
||
| require.NoError(t, testutil.GatherAndCompare(reg, strings.NewReader(` | ||
| # HELP rate_limit_logger_discarded_log_lines_total Total number of discarded log lines per level. | ||
| # TYPE rate_limit_logger_discarded_log_lines_total counter | ||
| rate_limit_logger_discarded_log_lines_total{level="debug"} 1 | ||
| rate_limit_logger_discarded_log_lines_total{level="error"} 1 | ||
| rate_limit_logger_discarded_log_lines_total{level="warning"} 2 | ||
| `))) | ||
| } | ||
|
|
||
| func TestRateLimitedLoggerWithFields(t *testing.T) { | ||
| buf := bytes.NewBuffer(nil) | ||
| c := newCounterLogger(buf) | ||
| reg := prometheus.NewPedanticRegistry() | ||
| logger := NewRateLimitedLogger(c, 0.0001, 1, reg) | ||
| loggerWithFields := logger.WithField("key", "value") | ||
|
|
||
| loggerWithFields.Errorln("Error will be logged") | ||
| assert.Equal(t, 1, c.count) | ||
| c.verify(t, []string{"key", "value", "error", "Error will be logged"}) | ||
|
|
||
| logger.Infoln("Info will not be logged") | ||
| loggerWithFields.Debugln("Debug will not be logged") | ||
| loggerWithFields.Warnln("Warning will not be logged") | ||
| assert.Equal(t, 1, c.count) | ||
|
|
||
| require.NoError(t, testutil.GatherAndCompare(reg, strings.NewReader(` | ||
| # HELP rate_limit_logger_discarded_log_lines_total Total number of discarded log lines per level. | ||
| # TYPE rate_limit_logger_discarded_log_lines_total counter | ||
| rate_limit_logger_discarded_log_lines_total{level="info"} 1 | ||
| rate_limit_logger_discarded_log_lines_total{level="debug"} 1 | ||
| rate_limit_logger_discarded_log_lines_total{level="warning"} 1 | ||
| `))) | ||
| } | ||
|
|
||
| type counterLogger struct { | ||
| logger Interface | ||
| buf *bytes.Buffer | ||
| count int | ||
| } | ||
|
|
||
| func (c *counterLogger) Debugf(format string, args ...interface{}) { | ||
| c.logger.Debugf(format, args...) | ||
| c.count++ | ||
| } | ||
|
|
||
| func (c *counterLogger) Debugln(args ...interface{}) { | ||
| c.logger.Debugln(args...) | ||
| c.count++ | ||
| } | ||
|
|
||
| func (c *counterLogger) Infof(format string, args ...interface{}) { | ||
| c.logger.Infof(format, args...) | ||
| c.count++ | ||
| } | ||
|
|
||
| func (c *counterLogger) Infoln(args ...interface{}) { | ||
| c.logger.Infoln(args...) | ||
| c.count++ | ||
| } | ||
|
|
||
| func (c *counterLogger) Warnf(format string, args ...interface{}) { | ||
| c.logger.Warnf(format, args...) | ||
| c.count++ | ||
| } | ||
|
|
||
| func (c *counterLogger) Warnln(args ...interface{}) { | ||
| c.logger.Warnln(args...) | ||
| c.count++ | ||
| } | ||
|
|
||
| func (c *counterLogger) Errorf(format string, args ...interface{}) { | ||
| c.logger.Errorf(format, args...) | ||
| c.count++ | ||
| } | ||
|
|
||
| func (c *counterLogger) Errorln(args ...interface{}) { | ||
| c.logger.Errorln(args...) | ||
| c.count++ | ||
| } | ||
|
|
||
| func (c *counterLogger) WithField(key string, value interface{}) Interface { | ||
| c.logger = c.logger.WithField(key, value) | ||
| return c | ||
| } | ||
|
|
||
| func (c *counterLogger) WithFields(fields Fields) Interface { | ||
| c.logger = c.logger.WithFields(fields) | ||
| return c | ||
| } | ||
|
|
||
| func (c *counterLogger) verify(t *testing.T, logContains []string) { | ||
duricanikolic marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| for _, content := range logContains { | ||
| require.True(t, bytes.Contains(c.buf.Bytes(), []byte(content))) | ||
| } | ||
| } | ||
|
|
||
| func newCounterLogger(buf *bytes.Buffer) *counterLogger { | ||
| logrusLogger := logrus.New() | ||
| logrusLogger.Out = buf | ||
| logrusLogger.Level = logrus.DebugLevel | ||
| return &counterLogger{ | ||
| logger: Logrus(logrusLogger), | ||
| buf: buf, | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.