Turn timer helper into a struct with methods

This commit is contained in:
beorn7 2016-11-10 18:30:43 +01:00
parent d845abb9f9
commit 8496756f6d
2 changed files with 30 additions and 8 deletions

View File

@ -15,15 +15,37 @@ package prometheus
import "time" import "time"
type Observable interface { // Observer is the interface that wraps the Observe method, used by Histogram
// and Summary to add observations.
type Observer interface {
Observe(float64) Observe(float64)
} }
type TimerFunc func(Observable) type Timer struct {
begin time.Time
observer Observer
gauge Gauge
}
func NewTimer() TimerFunc { func StartTimer() *Timer {
begin := time.Now() return &Timer{begin: time.Now()}
return func(obs Observable) { }
obs.Observe(time.Since(begin).Seconds())
func (t *Timer) With(o Observer) *Timer {
t.observer = o
return t
}
func (t *Timer) WithGauge(g Gauge) *Timer {
t.gauge = g
return t
}
func (t *Timer) Stop() {
if t.observer != nil {
t.observer.Observe(time.Since(t.begin).Seconds())
}
if t.gauge != nil {
t.gauge.Set(time.Since(t.begin).Seconds())
} }
} }

View File

@ -26,8 +26,8 @@ func TestTimerObserve(t *testing.T) {
}, },
) )
stop := NewTimer() timer := StartTimer().With(his)
stop(his) timer.Stop()
m := &dto.Metric{} m := &dto.Metric{}
his.Write(m) his.Write(m)