alert.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //go:build linux
  2. // +build linux
  3. package stat
  4. import (
  5. "flag"
  6. "fmt"
  7. "strings"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "github.com/zeromicro/go-zero/core/executors"
  12. "github.com/zeromicro/go-zero/core/logx"
  13. "github.com/zeromicro/go-zero/core/proc"
  14. "github.com/zeromicro/go-zero/core/sysx"
  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. builder.WriteString(fmt.Sprintln(time.Now().Format(timeFormat)))
  42. if len(clusterName) > 0 {
  43. builder.WriteString(fmt.Sprintf("cluster: %s\n", clusterName))
  44. }
  45. builder.WriteString(fmt.Sprintf("host: %s\n", sysx.Hostname()))
  46. dp := atomic.SwapInt32(&dropped, 0)
  47. if dp > 0 {
  48. builder.WriteString(fmt.Sprintf("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. }