github.com/cilium/cilium@v1.16.2/pkg/logging/limiter.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package logging
     5  
     6  import (
     7  	"time"
     8  
     9  	"golang.org/x/time/rate"
    10  )
    11  
    12  // Limiter is a wrapper around rate.Limiter that does not panic when
    13  // the limiter is uninitialized. The wrapping also allows more logging
    14  // specific functionality to be added later without changing all the call
    15  // sites.
    16  type Limiter struct {
    17  	bucket *rate.Limiter
    18  }
    19  
    20  // NewLimiter returns a new Limiter allowing log messages to be
    21  // emitted on average once every 'interval' and upto 'burst' messages
    22  // during any 'interval'.
    23  func NewLimiter(interval time.Duration, burst int) Limiter {
    24  	return Limiter{
    25  		bucket: rate.NewLimiter(rate.Every(interval), burst),
    26  	}
    27  }
    28  
    29  // Allow returns true if the log message is allowed under the
    30  // configured rate limit.
    31  func (ll Limiter) Allow() bool {
    32  	if ll.bucket == nil {
    33  		return true // limiter not initialized => no limit
    34  	}
    35  	return ll.bucket.Allow()
    36  }