This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
timer.go
66 lines (57 loc) · 1.52 KB
/
timer.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
package metrics
import (
"sync"
"time"
)
// Timer tracks the time a metric
type Timer struct {
client Client
name string
tags []string
}
// TimerContext is the context for an in-flight datapoint
type TimerContext struct {
stateMu sync.Mutex
timer *Timer
start time.Time
stopped bool
additionalTags []TagOption
}
// NewTimer returns a new Timer
func NewTimer(client Client, name string, tagOptions ...TagOption) (*Timer, error) {
if err := validateMetricName(name); err != nil {
return nil, err
}
return &Timer{
client: client,
name: name,
tags: GetTags(tagOptions...),
}, nil
}
// Time begins tracking a new datapoint. Use TimerContext.Stop on the
// returned context to record the time passed since calling Time
func (t *Timer) Time(tags ...TagOption) *TimerContext {
return &TimerContext{
start: time.Now(),
timer: t,
additionalTags: tags,
}
}
// AddTiming emits a timing value that has already been observed
func (t *Timer) AddTiming(value time.Duration, tags ...TagOption) {
t.submitTiming(value, tags)
}
func (t *Timer) submitTiming(value time.Duration, additionalTags []TagOption) {
tags := append(t.tags, GetTags(additionalTags...)...)
_ = t.client.Timing(t.name, value, tags)
}
// Stop records the time since the context's creation if it hasn't already
// been stopped
func (tc *TimerContext) Stop() {
tc.stateMu.Lock()
if !tc.stopped {
tc.timer.submitTiming(time.Since(tc.start), tc.additionalTags)
tc.stopped = true
}
tc.stateMu.Unlock()
}