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