forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alert.go
72 lines (63 loc) · 1.43 KB
/
alert.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// +build linux
package stat
import (
"flag"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/tal-tech/go-zero/core/executors"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/proc"
"github.com/tal-tech/go-zero/core/sysx"
"github.com/tal-tech/go-zero/core/timex"
)
const (
clusterNameKey = "CLUSTER_NAME"
testEnv = "test.v"
timeFormat = "2006-01-02 15:04:05"
)
var (
reporter = logx.Alert
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.
func Report(msg string) {
lock.RLock()
fn := reporter
lock.RUnlock()
if fn != nil {
reported := lessExecutor.DoOrDiscard(func() {
var builder strings.Builder
fmt.Fprintf(&builder, "%s\n", timex.Time().Format(timeFormat))
if len(clusterName) > 0 {
fmt.Fprintf(&builder, "cluster: %s\n", clusterName)
}
fmt.Fprintf(&builder, "host: %s\n", sysx.Hostname())
dp := atomic.SwapInt32(&dropped, 0)
if dp > 0 {
fmt.Fprintf(&builder, "dropped: %d\n", dp)
}
builder.WriteString(strings.TrimSpace(msg))
fn(builder.String())
})
if !reported {
atomic.AddInt32(&dropped, 1)
}
}
}
// SetReporter sets the given reporter.
func SetReporter(fn func(string)) {
lock.Lock()
defer lock.Unlock()
reporter = fn
}