-
Notifications
You must be signed in to change notification settings - Fork 18
/
statsd.go
73 lines (61 loc) · 1.43 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
// Client library for statsd.
package statsd
import (
"bufio"
"fmt"
"io"
"math/rand"
"net"
"time"
)
type Client struct {
Name string
rw *bufio.ReadWriter
}
func millisecond(d time.Duration) int {
return int(d.Seconds() * 1000)
}
func Dial(addr string) (*Client, error) {
rw, err := net.Dial("udp", addr)
if err != nil {
return nil, err
}
return newClient(addr, rw), nil
}
func newClient(name string, rw io.ReadWriter) *Client {
c := new(Client)
c.Name = name
c.rw = bufio.NewReadWriter(bufio.NewReader(rw), bufio.NewWriter(rw))
return c
}
func (c *Client) Increment(stat string, count int, rate float64) error {
return c.Send(stat, rate, "%d|c", count)
}
func (c *Client) Decrement(stat string, count int, rate float64) error {
return c.Increment(stat, -count, rate)
}
func (c *Client) Timing(stat string, delta int, rate float64) error {
return c.Send(stat, rate, "%d|ms", delta)
}
func (c *Client) Time(stat string, rate float64, f func()) error {
ts := time.Now()
f()
delta := millisecond(time.Now().Sub(ts))
return c.Timing(stat, delta, rate)
}
func (c *Client) Send(stat string, rate float64, format string, args ...interface{}) error {
if rate < 1 {
if rand.Float64() < rate {
format = fmt.Sprintf("%s|@%1.2f", format, rate)
} else {
return nil
}
}
format = fmt.Sprintf("%s:%s", stat, format)
_, err := fmt.Fprintf(c.rw, format, args...)
if err != nil {
return err
}
err = c.rw.Flush()
return err
}