gauge.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package metrics
  2. import "sync/atomic"
  3. // Gauges hold an int64 value that can be set arbitrarily.
  4. type Gauge interface {
  5. Update(int64)
  6. Value() int64
  7. }
  8. // GetOrRegisterGauge returns an existing Gauge or constructs and registers a
  9. // new StandardGauge.
  10. func GetOrRegisterGauge(name string, r Registry) Gauge {
  11. if nil == r {
  12. r = DefaultRegistry
  13. }
  14. return r.GetOrRegister(name, NewGauge()).(Gauge)
  15. }
  16. // NewGauge constructs a new StandardGauge.
  17. func NewGauge() Gauge {
  18. if UseNilMetrics {
  19. return NilGauge{}
  20. }
  21. return &StandardGauge{0}
  22. }
  23. // NewRegisteredGauge constructs and registers a new StandardGauge.
  24. func NewRegisteredGauge(name string, r Registry) Gauge {
  25. c := NewGauge()
  26. if nil == r {
  27. r = DefaultRegistry
  28. }
  29. r.Register(name, c)
  30. return c
  31. }
  32. // No-op Gauge.
  33. type NilGauge struct{}
  34. // No-op.
  35. func (NilGauge) Update(v int64) {}
  36. // Value is a no-op.
  37. func (NilGauge) Value() int64 { return 0 }
  38. // StandardGauge is the standard implementation of a Gauge and uses the
  39. // sync/atomic package to manage a single int64 value.
  40. type StandardGauge struct {
  41. value int64
  42. }
  43. // Update the gauge's value.
  44. func (g *StandardGauge) Update(v int64) {
  45. atomic.StoreInt64(&g.value, v)
  46. }
  47. // Value returns the gauge's current value.
  48. func (g *StandardGauge) Value() int64 {
  49. return atomic.LoadInt64(&g.value)
  50. }