forked from infinilabs/crawler
/
statsd.go
118 lines (94 loc) · 2.37 KB
/
statsd.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package stats
import (
"fmt"
log "github.com/cihub/seelog"
. "github.com/medcl/gopa/core/config"
"github.com/medcl/gopa/core/stats"
"github.com/quipo/statsd"
"sync"
"time"
)
type StatsDConfig struct {
Host string `config:"host"`
Port int `config:"port"`
Namespace string `config:"namespace"`
IntervalInSeconds time.Duration `config:"interval_in_seconds"`
}
type StatsDModule struct {
}
var statsdInited bool
var statsdclient *statsd.StatsdClient
var buffer *statsd.StatsdBuffer
var l1 sync.RWMutex
var defaultStatsdConfig = StatsDConfig{
Host: "localhost",
Port: 8125,
Namespace: "gopa.",
IntervalInSeconds: 1,
}
func (this StatsDModule) Name() string {
return "StatsD"
}
func (this StatsDModule) Start(cfg *Config) {
if statsdInited {
return
}
config := defaultStatsdConfig
cfg.Unpack(&config)
addr := fmt.Sprintf("%s:%d", config.Host, config.Port)
l1.Lock()
defer l1.Unlock()
statsdclient = statsd.NewStatsdClient(addr, config.Namespace)
log.Debug("statsd connec to, ", addr, ",prefix:", config.Namespace)
err := statsdclient.CreateSocket()
if nil != err {
log.Warn(err)
return
}
interval := time.Second * config.IntervalInSeconds // aggregate stats and flush every 2 seconds
buffer = statsd.NewStatsdBuffer(interval, statsdclient)
statsdInited = true
stats.Register(this)
}
func (this StatsDModule) Stop() error {
if statsdclient != nil {
statsdclient.Close()
}
return nil
}
func (this StatsDModule) Increment(category, key string) {
this.IncrementBy(category, key, 1)
}
func (this StatsDModule) IncrementBy(category, key string, value int64) {
if !statsdInited {
return
}
buffer.Incr(category+"."+key, value)
}
func (this StatsDModule) Decrement(category, key string) {
this.DecrementBy(category, key, 1)
}
func (this StatsDModule) DecrementBy(category, key string, value int64) {
if !statsdInited {
return
}
buffer.Decr(category+"."+key, value)
}
func (this StatsDModule) Timing(category, key string, v int64) {
if !statsdInited {
return
}
buffer.Timing(category+"."+key, v)
}
func (this StatsDModule) Gauge(category, key string, v int64) {
if !statsdInited {
return
}
buffer.Gauge(category+"."+key, v)
}
func (this StatsDModule) Stat(category, key string) int64 {
return 0
}
func (this StatsDModule) StatsAll() *[]byte {
return nil
}