forked from cv-library/statsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatsd.go
124 lines (93 loc) · 2.13 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
119
120
121
122
123
124
package statsd
import (
"net"
"os"
"strconv"
"time"
)
// Address of the StatsD server.
var Address = "localhost:8125"
// AlsoAppendHost appends hostname along with any metric sent.
var AlsoAppendHost = true
// Cache the conn for perf.
var conn net.Conn
var host string
func init() {
var err error
if host, err = os.Hostname(); err != nil {
panic(err)
}
}
func Timer() timer {
return timer{time.Now()}
}
// Timer
type timer struct {
start time.Time
}
func (t *timer) Reset() {
t.start = time.Now()
}
func (t *timer) Send(names ...interface{}) (took time.Duration) {
took = time.Since(t.start)
if err := getConnection(); err != nil {
return
}
value := ":" + strconv.FormatUint(uint64(took.Nanoseconds()/1e6), 10) + "|ms"
for _, name := range names {
conn.Write([]byte(name.(string) + value))
// Send a host suffixed stat too.
if AlsoAppendHost {
conn.Write([]byte(name.(string) + "." + host + value))
}
}
return
}
// Gauge sets arbitrary numeric value for a given metric.
func Gauge(name string, value int64) {
if err := getConnection(); err != nil {
return
}
suffix := ":" + strconv.FormatInt(value, 10) + "|g"
conn.Write([]byte(name + suffix))
// Send a host suffixed stat too.
if AlsoAppendHost {
conn.Write([]byte(name + "." + host + suffix))
}
return
}
// Inc is a simple counter adding one to a given metric.
func Inc(name string) {
if err := getConnection(); err != nil {
return
}
conn.Write([]byte(name + ":1|c"))
// Send a host suffixed stat too.
if AlsoAppendHost {
conn.Write([]byte(name + "." + host + ":1|c"))
}
return
}
// Time sends duration in ms for a given metric.
func Time(name string, took time.Duration) {
if err := getConnection(); err != nil {
return
}
value := ":" + strconv.FormatUint(uint64(took.Nanoseconds()/1e6), 10) + "|ms"
conn.Write([]byte(name + value))
// Send a host suffixed stat too.
if AlsoAppendHost {
conn.Write([]byte(name + "." + host + value))
}
return
}
func getConnection() (err error) {
// If we don't have a conn, make one.
if conn == nil {
if conn, err = net.Dial("udp", Address); err != nil {
conn = nil
return
}
}
return
}