gauge.go 1.1 KB

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