alert.go 1.3 KB

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