-
Notifications
You must be signed in to change notification settings - Fork 458
/
latency.go
55 lines (50 loc) · 1.49 KB
/
latency.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
package telemetry
import (
"sync"
"time"
)
// Latency is used to track timing between two specific events. It
// is a generic version of CallCounter and can be used to measure latency between any two events.
//
// Example:
//
// func Foo() {
// latency := StartLatencyMetric(metrics, "foo")
// call.AddLabel("food", "burgers")
// // do something
// latency.Measure()
// // do other things
// }
//
// Instances of this struct should only be created directly by this package
// and its subpackages, which define the specific metrics that are emitted.
// It is left exported for testing purposes.
type Latency struct {
metrics Metrics
key []string
labels []Label
start time.Time
mu sync.Mutex
}
// StartLatencyMetric starts a "call", which when finished via Done() will emit timing
// and error related metrics.
func StartLatencyMetric(metrics Metrics, key string, keyn ...string) *Latency {
return &Latency{
metrics: metrics,
key: append([]string{key}, keyn...),
start: time.Now(),
}
}
// AddLabel adds a label to be emitted with the call counter. It is safe to call
// from multiple goroutines.
func (l *Latency) AddLabel(name, value string) {
l.mu.Lock()
defer l.mu.Unlock()
l.labels = append(l.labels, Label{Name: name, Value: value})
}
// Measure emits a latency metric based on l.start along with labels configured.
func (l *Latency) Measure() {
l.mu.Lock()
defer l.mu.Unlock()
l.metrics.MeasureSinceWithLabels(append(l.key, ElapsedTime), l.start, l.labels)
}