-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmemsampler.go
77 lines (64 loc) · 1.81 KB
/
memsampler.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
package statsdig
import (
"fmt"
"sync"
"time"
)
// MemSampler is a sampler that gathers metrics in memory
// and allows the count of metrics to be queried.
// It's only usage is to test metric sampling on your application.
type MemSampler struct {
sync.Mutex
storage map[string]int
}
func NewMemSampler() *MemSampler {
return &MemSampler{
storage: map[string]int{},
}
}
func (s *MemSampler) Count(name string, tags ...Tag) error {
serialized := serializeCount(name, tags)
s.add(serialized)
return nil
}
func (s *MemSampler) GetCount(name string, tags ...Tag) int {
serialized := serializeCount(name, tags)
return s.get(serialized)
}
func (s *MemSampler) Gauge(name string, value int, tags ...Tag) error {
serialized := serializeGauge(name, value, tags)
s.add(serialized)
return nil
}
func (s *MemSampler) GetGauge(name string, value int, tags ...Tag) int {
serialized := serializeGauge(name, value, tags)
return s.get(serialized)
}
func (s *MemSampler) Time(name string, value time.Duration, tags ...Tag) error {
serialized := serializeTime(name, value, tags)
s.add(serialized)
return nil
}
func (s *MemSampler) GetTime(name string, value time.Duration, tags ...Tag) int {
serialized := serializeTime(name, value, tags)
return s.get(serialized)
}
func serializeCount(name string, tags []Tag) string {
return fmt.Sprintf("count:%s:%v", name, tags)
}
func serializeGauge(name string, value int, tags []Tag) string {
return fmt.Sprintf("gauge:%s:%d:%v", name, value, tags)
}
func serializeTime(name string, value time.Duration, tags []Tag) string {
return fmt.Sprintf("time:%s:%d:%v", name, value, tags)
}
func (s *MemSampler) add(serialized string) {
s.Lock()
s.storage[serialized] += 1
s.Unlock()
}
func (s *MemSampler) get(serialized string) int {
s.Lock()
defer s.Unlock()
return s.storage[serialized]
}