forked from marpaia/graphite-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metric.go
69 lines (59 loc) · 1.35 KB
/
metric.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
package graphite
import (
"fmt"
"regexp"
"strings"
"time"
)
// Metric is a struct that defines the relevant properties of a graphite metric
type Metric struct {
Name string
Value string
Timestamp int64
Tags map[string]string
}
func NewMetric(name, value string, timestamp int64) Metric {
return Metric{
Name: name,
Value: value,
Timestamp: timestamp,
Tags: make(map[string]string),
}
}
func NewMetricWithTags(name, value string, timestamp int64, tags map[string]string) Metric {
return Metric{
Name: name,
Value: value,
Timestamp: timestamp,
Tags: tags,
}
}
func (metric Metric) IsUninitialized() bool {
return metric.Name == "" && metric.Value == "" && metric.Timestamp == 0
}
func (metric Metric) convertTags() string {
whitespace := regexp.MustCompile(`\s`)
builder := strings.Builder{}
if metric.Tags == nil || len(metric.Tags) == 0 {
return ""
}
for k, v := range metric.Tags {
if whitespace.MatchString(k) || whitespace.MatchString(v) {
continue
}
builder.WriteString(";")
builder.WriteString(k)
builder.WriteString("=")
builder.WriteString(v)
}
return builder.String()
}
func (metric Metric) String() string {
return fmt.Sprintf(
"%s%s %s %s",
metric.Name,
metric.convertTags(),
metric.Value,
time.Unix(metric.Timestamp, 0).Format("2006-01-02 15:04:05"),
)
}