alert.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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/logx"
  12. "github.com/tal-tech/go-zero/core/proc"
  13. "github.com/tal-tech/go-zero/core/sysx"
  14. "github.com/tal-tech/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. func Report(msg string) {
  34. lock.RLock()
  35. fn := reporter
  36. lock.RUnlock()
  37. if fn != nil {
  38. reported := lessExecutor.DoOrDiscard(func() {
  39. var builder strings.Builder
  40. fmt.Fprintf(&builder, "%s\n", timex.Time().Format(timeFormat))
  41. if len(clusterName) > 0 {
  42. fmt.Fprintf(&builder, "cluster: %s\n", clusterName)
  43. }
  44. fmt.Fprintf(&builder, "host: %s\n", sysx.Hostname())
  45. dp := atomic.SwapInt32(&dropped, 0)
  46. if dp > 0 {
  47. fmt.Fprintf(&builder, "dropped: %d\n", dp)
  48. }
  49. builder.WriteString(strings.TrimSpace(msg))
  50. fn(builder.String())
  51. })
  52. if !reported {
  53. atomic.AddInt32(&dropped, 1)
  54. }
  55. }
  56. }
  57. func SetReporter(fn func(string)) {
  58. lock.Lock()
  59. defer lock.Unlock()
  60. reporter = fn
  61. }