gauge.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. // Get an existing or create and register a new Gauge.
  12. func GetOrRegisterGauge(name string, r Registry) Gauge {
  13. if nil == r {
  14. r = DefaultRegistry
  15. }
  16. return r.GetOrRegister(name, NewGauge()).(Gauge)
  17. }
  18. // Create a new Gauge.
  19. func NewGauge() Gauge {
  20. if UseNilMetrics {
  21. return NilGauge{}
  22. }
  23. return &StandardGauge{0}
  24. }
  25. // Create and register a new Gauge.
  26. func NewRegisteredGauge(name string, r Registry) Gauge {
  27. c := NewGauge()
  28. if nil == r {
  29. r = DefaultRegistry
  30. }
  31. r.Register(name, c)
  32. return c
  33. }
  34. // No-op Gauge.
  35. type NilGauge struct{}
  36. // No-op.
  37. func (g NilGauge) Update(v int64) {}
  38. // No-op.
  39. func (g NilGauge) Value() int64 { return 0 }
  40. // The standard implementation of a Gauge uses the sync/atomic package
  41. // to manage a single int64 value.
  42. type StandardGauge struct {
  43. value int64
  44. }
  45. // Update the gauge's value.
  46. func (g *StandardGauge) Update(v int64) {
  47. atomic.StoreInt64(&g.value, v)
  48. }
  49. // Return the gauge's current value.
  50. func (g *StandardGauge) Value() int64 {
  51. return atomic.LoadInt64(&g.value)
  52. }