Skip to content

Commit

Permalink
Options to control logging.
Browse files Browse the repository at this point in the history
  • Loading branch information
udhos committed Mar 2, 2024
1 parent 2af15f5 commit 0cd801f
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions ratelimit/ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ type Options struct {

// GroupcacheSizeBytes limits the cache size. If unspecified, defaults to 10MB.
GroupcacheSizeBytes int64

// Logf provides logging function, if undefined defaults to log.Printf
Logf func(format string, v ...any)

// Debug enables debug logging.
Debug bool
}

// Limiter implements rate limiting.
Expand All @@ -57,6 +63,10 @@ func New(options Options) *Limiter {
panic("groupcache workspace is nil")
}

if options.Logf == nil {
options.Logf = log.Printf
}

lim := Limiter{
options: options,
}
Expand Down Expand Up @@ -86,7 +96,8 @@ func New(options Options) *Limiter {
return dest.SetBytes(data, count.Expire)
})

lim.group = groupcache.NewGroupWithWorkspace(options.GroupcacheWorkspace, cacheName, cacheSizeBytes, getter)
lim.group = groupcache.NewGroupWithWorkspace(options.GroupcacheWorkspace,
cacheName, cacheSizeBytes, getter)

return &lim
}
Expand Down Expand Up @@ -122,7 +133,7 @@ func (l *Limiter) Consume(ctx context.Context, key string) (bool, error) {

// 1/2: remove key
if errRemove := l.group.Remove(ctx, key); errRemove != nil {
log.Printf("ratelimit.Consume: remove key='%s' error: %v",
l.options.Logf("ERROR: ratelimit.Consume: remove key='%s' error: %v",
key, errRemove)
}

Expand All @@ -146,8 +157,10 @@ func (l *Limiter) Consume(ctx context.Context, key string) (bool, error) {

accept := !expired && count.Value <= l.options.Slots

log.Printf("ratelimit.Consume: key='%s' count=%d/%d interval=%v/%v expired=%t accept=%t",
key, count.Value, l.options.Slots, remain, l.options.Interval, expired, accept)
if l.options.Debug {
l.options.Logf("DEBUG: ratelimit.Consume: key='%s' count=%d/%d interval=%v/%v expired=%t accept=%t",
key, count.Value, l.options.Slots, remain, l.options.Interval, expired, accept)
}

return accept, nil
}
Expand Down

0 comments on commit 0cd801f

Please sign in to comment.