cloudflare/cloudflared

Public

mirrored from https://github.com/cloudflare/cloudflaredAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2019.11.2

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

metrics/timer.go

47lines · modecode

1package metrics
2
3import (
4 "time"
5 "github.com/prometheus/client_golang/prometheus"
6)
7
8// Timer assumes the metrics is partitioned by one label
9type Timer struct {
10 startTime map[string]time.Time
11 metrics *prometheus.HistogramVec
12 measureUnit time.Duration
13 labelKey string
14}
15
16func NewTimer(metrics *prometheus.HistogramVec, unit time.Duration, labelKey string) *Timer {
17 return &Timer{
18 startTime: make(map[string]time.Time),
19 measureUnit: unit,
20 metrics: metrics,
21 labelKey: labelKey,
22 }
23}
24
25func (i *Timer) Start(labelVal string) {
26 i.startTime[labelVal] = time.Now()
27}
28
29func (i *Timer) End(labelVal string) time.Duration {
30 if start, ok := i.startTime[labelVal]; ok {
31 return Latency(start, time.Now())
32 }
33 return 0
34}
35
36func (i *Timer) Observe(measurement time.Duration, labelVal string) {
37 metricsLabels := prometheus.Labels{i.labelKey: labelVal}
38 i.metrics.With(metricsLabels).Observe(float64(measurement / i.measureUnit))
39}
40
41func (i *Timer) EndAndObserve(labelVal string) {
42 i.Observe(i.End(labelVal), labelVal)
43}
44
45func Latency(startTime, endTime time.Time) time.Duration {
46 return endTime.Sub(startTime)
47}
48