timer.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package metrics
  2. import (
  3. "time"
  4. "github.com/prometheus/client_golang/prometheus"
  5. )
  6. // StartTimer begins a timer observation at the callsite. When the target
  7. // operation is completed, the caller should call the return done func().
  8. func StartTimer(timer Timer) (done func()) {
  9. start := time.Now()
  10. return func() {
  11. timer.Update(time.Since(start))
  12. }
  13. }
  14. // Timer is a metric that allows collecting the duration of an action in seconds
  15. type Timer interface {
  16. // Update records an observation, duration, and converts to the target
  17. // units.
  18. Update(duration time.Duration)
  19. // UpdateSince will add the duration from the provided starting time to the
  20. // timer's summary with the precisions that was used in creation of the timer
  21. UpdateSince(time.Time)
  22. }
  23. // LabeledTimer is a timer that must have label values populated before use.
  24. type LabeledTimer interface {
  25. WithValues(labels ...string) Timer
  26. }
  27. type labeledTimer struct {
  28. m *prometheus.HistogramVec
  29. }
  30. func (lt *labeledTimer) WithValues(labels ...string) Timer {
  31. return &timer{m: lt.m.WithLabelValues(labels...)}
  32. }
  33. func (lt *labeledTimer) Describe(c chan<- *prometheus.Desc) {
  34. lt.m.Describe(c)
  35. }
  36. func (lt *labeledTimer) Collect(c chan<- prometheus.Metric) {
  37. lt.m.Collect(c)
  38. }
  39. type timer struct {
  40. m prometheus.Histogram
  41. }
  42. func (t *timer) Update(duration time.Duration) {
  43. t.m.Observe(duration.Seconds())
  44. }
  45. func (t *timer) UpdateSince(since time.Time) {
  46. t.m.Observe(time.Since(since).Seconds())
  47. }
  48. func (t *timer) Describe(c chan<- *prometheus.Desc) {
  49. t.m.Describe(c)
  50. }
  51. func (t *timer) Collect(c chan<- prometheus.Metric) {
  52. t.m.Collect(c)
  53. }