alert.go 1.4 KB

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