Files
cloud-services/pkg/logger/limiter.go

46 lines
762 B
Go

package logger
import (
"sync"
"time"
"github.com/ReneKroon/ttlcache/v2"
)
func NewLogLimiter(duration time.Duration, limit int) *LogLimiter {
return &LogLimiter{
duration: duration,
limit: limit,
}
}
type LogLimiter struct {
duration time.Duration
limit int
cache *ttlcache.Cache
onceCache sync.Once
}
func (l *LogLimiter) Check(message string) bool {
_, err := l.logCache().Get(message)
if err == ttlcache.ErrNotFound {
l.logCache().Set(message, true)
return true
}
return false
}
func (l *LogLimiter) logCache() *ttlcache.Cache {
l.onceCache.Do(func() {
if l.cache == nil {
cache := ttlcache.NewCache()
cache.SetTTL(l.duration)
cache.SetCacheSizeLimit(l.limit)
l.cache = cache
}
})
return l.cache
}