alert.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // +build linux
  2. package stat
  3. import (
  4. "flag"
  5. "fmt"
  6. "strings"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "git.i2edu.net/i2/go-zero/core/executors"
  11. "git.i2edu.net/i2/go-zero/core/logx"
  12. "git.i2edu.net/i2/go-zero/core/proc"
  13. "git.i2edu.net/i2/go-zero/core/sysx"
  14. "git.i2edu.net/i2/go-zero/core/timex"
  15. )
  16. const (
  17. clusterNameKey = "CLUSTER_NAME"
  18. testEnv = "test.v"
  19. timeFormat = "2006-01-02 15:04:05"
  20. )
  21. var (
  22. reporter = logx.Alert
  23. lock sync.RWMutex
  24. lessExecutor = executors.NewLessExecutor(time.Minute * 5)
  25. dropped int32
  26. clusterName = proc.Env(clusterNameKey)
  27. )
  28. func init() {
  29. if flag.Lookup(testEnv) != nil {
  30. SetReporter(nil)
  31. }
  32. }
  33. // Report reports given message.
  34. func Report(msg string) {
  35. lock.RLock()
  36. fn := reporter
  37. lock.RUnlock()
  38. if fn != nil {
  39. reported := lessExecutor.DoOrDiscard(func() {
  40. var builder strings.Builder
  41. fmt.Fprintf(&builder, "%s\n", timex.Time().Format(timeFormat))
  42. if len(clusterName) > 0 {
  43. fmt.Fprintf(&builder, "cluster: %s\n", clusterName)
  44. }
  45. fmt.Fprintf(&builder, "host: %s\n", sysx.Hostname())
  46. dp := atomic.SwapInt32(&dropped, 0)
  47. if dp > 0 {
  48. fmt.Fprintf(&builder, "dropped: %d\n", dp)
  49. }
  50. builder.WriteString(strings.TrimSpace(msg))
  51. fn(builder.String())
  52. })
  53. if !reported {
  54. atomic.AddInt32(&dropped, 1)
  55. }
  56. }
  57. }
  58. // SetReporter sets the given reporter.
  59. func SetReporter(fn func(string)) {
  60. lock.Lock()
  61. defer lock.Unlock()
  62. reporter = fn
  63. }