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