forked from nsqio/nsq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statsd_client.go
63 lines (52 loc) · 1.19 KB
/
statsd_client.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
package util
import (
"errors"
"fmt"
"net"
"time"
)
type StatsdClient struct {
conn net.Conn
addr string
prefix string
}
func NewStatsdClient(addr string, prefix string) *StatsdClient {
return &StatsdClient{
addr: addr,
prefix: prefix,
}
}
func (c *StatsdClient) String() string {
return c.addr
}
func (c *StatsdClient) CreateSocket() error {
conn, err := net.DialTimeout("udp", c.addr, time.Second)
if err != nil {
return err
}
c.conn = conn
return nil
}
func (c *StatsdClient) Close() error {
return c.conn.Close()
}
func (c *StatsdClient) Incr(stat string, count int64) error {
return c.send(stat, "%d|c", count)
}
func (c *StatsdClient) Decr(stat string, count int64) error {
return c.send(stat, "%d|c", -count)
}
func (c *StatsdClient) Timing(stat string, delta int64) error {
return c.send(stat, "%d|ms", delta)
}
func (c *StatsdClient) Gauge(stat string, value int64) error {
return c.send(stat, "%d|g", value)
}
func (c *StatsdClient) send(stat string, format string, value int64) error {
if c.conn == nil {
return errors.New("not connected")
}
format = fmt.Sprintf("%s%s:%s", c.prefix, stat, format)
_, err := fmt.Fprintf(c.conn, format, value)
return err
}