-
Notifications
You must be signed in to change notification settings - Fork 3
/
measures.go
116 lines (100 loc) · 2.11 KB
/
measures.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
// Copyright 2015 Measures authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package measures
import (
"encoding/json"
"errors"
"net"
"time"
)
type Dimensions map[string]interface{}
type Client interface {
Connect() error
Disconnect() error
Write(b []byte) (int, error)
}
type client struct {
address string
conn net.Conn
}
func NewClient(address string) Client {
return &client{address: address}
}
func (c *client) Connect() (err error) {
c.conn, err = net.Dial("udp", c.address)
return err
}
func (c *client) Disconnect() (err error) {
if c.conn != nil {
return c.conn.Close()
}
return nil
}
func (c *client) Write(b []byte) (n int, err error) {
if c.conn == nil {
err = c.Connect()
if err != nil {
return 0, err
}
}
n, err = c.conn.Write(b)
if err == nil {
return n, nil
}
err = c.Connect()
if err != nil {
return 0, err
}
return c.conn.Write(b)
}
type Measures struct {
client Client
clientName string
}
func New(client, address string) *Measures {
m := Measures{clientName: client}
if address != "" {
m.client = NewClient(address)
}
return &m
}
func (m *Measures) send(d Dimensions) (n int, err error) {
b, err := json.Marshal(d)
if err != nil {
return 0, err
}
if m.client == nil {
return 0, errors.New("no client set")
}
return m.client.Write(b)
}
func (m *Measures) CleanUp() {
m.client.Disconnect()
}
func (m *Measures) Count(metric string, counter int, dimensions Dimensions) (err error) {
d := make(Dimensions, len(dimensions)+3)
d["client"] = m.clientName
d["count"] = counter
d["metric"] = metric
for k, v := range dimensions {
d[k] = v
}
_, err = m.send(d)
return err
}
func (m *Measures) SetClient(client Client) (err error) {
m.client = client
return nil
}
func (m *Measures) Time(metric string, startTime time.Time, dimensions Dimensions) (err error) {
d := make(Dimensions, len(dimensions)+3)
d["client"] = m.clientName
d["metric"] = metric
d["time"] = time.Since(startTime).Seconds()
for k, v := range dimensions {
d[k] = v
}
_, err = m.send(d)
return err
}