limitedexecutor.go 832 B

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