You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/stat/alert.go

73 lines
1.4 KiB
Go

//go:build linux
4 years ago
// +build linux
package stat
import (
"flag"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/executors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/sysx"
4 years ago
)
const (
clusterNameKey = "CLUSTER_NAME"
testEnv = "test.v"
timeFormat = "2006-01-02 15:04:05"
)
var (
4 years ago
reporter = logx.Alert
4 years ago
lock sync.RWMutex
lessExecutor = executors.NewLessExecutor(time.Minute * 5)
dropped int32
clusterName = proc.Env(clusterNameKey)
)
func init() {
if flag.Lookup(testEnv) != nil {
SetReporter(nil)
}
}
// Report reports given message.
4 years ago
func Report(msg string) {
lock.RLock()
fn := reporter
lock.RUnlock()
if fn != nil {
reported := lessExecutor.DoOrDiscard(func() {
var builder strings.Builder
builder.WriteString(fmt.Sprintln(time.Now().Format(timeFormat)))
4 years ago
if len(clusterName) > 0 {
builder.WriteString(fmt.Sprintf("cluster: %s\n", clusterName))
4 years ago
}
builder.WriteString(fmt.Sprintf("host: %s\n", sysx.Hostname()))
4 years ago
dp := atomic.SwapInt32(&dropped, 0)
if dp > 0 {
builder.WriteString(fmt.Sprintf("dropped: %d\n", dp))
4 years ago
}
builder.WriteString(strings.TrimSpace(msg))
fn(builder.String())
})
if !reported {
atomic.AddInt32(&dropped, 1)
}
}
}
// SetReporter sets the given reporter.
4 years ago
func SetReporter(fn func(string)) {
lock.Lock()
defer lock.Unlock()
reporter = fn
}