You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool/nlog/limitedexecutor.go

41 lines
840 B
Go

1 year ago
package nlog
import (
natomic "git.noahlan.cn/noahlan/ntool/nsys/atomic"
"sync/atomic"
"time"
)
type limitedExecutor struct {
threshold time.Duration
lastTime *natomic.AtomicDuration
discarded uint32
}
func newLimitedExecutor(milliseconds int) *limitedExecutor {
return &limitedExecutor{
threshold: time.Duration(milliseconds) * time.Millisecond,
lastTime: natomic.NewAtomicDuration(),
}
}
func (le *limitedExecutor) logOrDiscard(execute func()) {
if le == nil || le.threshold <= 0 {
execute()
return
}
now := time.Since(time.Now().AddDate(-1, -1, -1))
if now-le.lastTime.Load() <= le.threshold {
atomic.AddUint32(&le.discarded, 1)
} else {
le.lastTime.Set(now)
discarded := atomic.SwapUint32(&le.discarded, 0)
if discarded > 0 {
Errorf("Discarded %d error messages", discarded)
}
execute()
}
}