github.com/lingyao2333/mo-zero@v1.4.1/core/logx/limitedexecutor.go (about) 1 package logx 2 3 import ( 4 "sync/atomic" 5 "time" 6 7 "github.com/lingyao2333/mo-zero/core/syncx" 8 "github.com/lingyao2333/mo-zero/core/timex" 9 ) 10 11 type limitedExecutor struct { 12 threshold time.Duration 13 lastTime *syncx.AtomicDuration 14 discarded uint32 15 } 16 17 func newLimitedExecutor(milliseconds int) *limitedExecutor { 18 return &limitedExecutor{ 19 threshold: time.Duration(milliseconds) * time.Millisecond, 20 lastTime: syncx.NewAtomicDuration(), 21 } 22 } 23 24 func (le *limitedExecutor) logOrDiscard(execute func()) { 25 if le == nil || le.threshold <= 0 { 26 execute() 27 return 28 } 29 30 now := timex.Now() 31 if now-le.lastTime.Load() <= le.threshold { 32 atomic.AddUint32(&le.discarded, 1) 33 } else { 34 le.lastTime.Set(now) 35 discarded := atomic.SwapUint32(&le.discarded, 0) 36 if discarded > 0 { 37 Errorf("Discarded %d error messages", discarded) 38 } 39 40 execute() 41 } 42 }