gauge.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package metrics
  2. import "sync/atomic"
  3. // Gauges hold an int64 value that can be set arbitrarily.
  4. type Gauge interface {
  5. Snapshot() Gauge
  6. Update(int64)
  7. Value() int64
  8. }
  9. // GetOrRegisterGauge returns an existing Gauge or constructs and registers a
  10. // new StandardGauge.
  11. func GetOrRegisterGauge(name string, r Registry) Gauge {
  12. if nil == r {
  13. r = DefaultRegistry
  14. }
  15. return r.GetOrRegister(name, NewGauge).(Gauge)
  16. }
  17. // NewGauge constructs a new StandardGauge.
  18. func NewGauge() Gauge {
  19. if UseNilMetrics {
  20. return NilGauge{}
  21. }
  22. return &StandardGauge{0}
  23. }
  24. // NewRegisteredGauge constructs and registers a new StandardGauge.
  25. func NewRegisteredGauge(name string, r Registry) Gauge {
  26. c := NewGauge()
  27. if nil == r {
  28. r = DefaultRegistry
  29. }
  30. r.Register(name, c)
  31. return c
  32. }
  33. // GaugeSnapshot is a read-only copy of another Gauge.
  34. type GaugeSnapshot int64
  35. // Snapshot returns the snapshot.
  36. func (g GaugeSnapshot) Snapshot() Gauge { return g }
  37. // Update panics.
  38. func (GaugeSnapshot) Update(int64) {
  39. panic("Update called on a GaugeSnapshot")
  40. }
  41. // Value returns the value at the time the snapshot was taken.
  42. func (g GaugeSnapshot) Value() int64 { return int64(g) }
  43. // NilGauge is a no-op Gauge.
  44. type NilGauge struct{}
  45. // Snapshot is a no-op.
  46. func (NilGauge) Snapshot() Gauge { return NilGauge{} }
  47. // Update is a no-op.
  48. func (NilGauge) Update(v int64) {}
  49. // Value is a no-op.
  50. func (NilGauge) Value() int64 { return 0 }
  51. // StandardGauge is the standard implementation of a Gauge and uses the
  52. // sync/atomic package to manage a single int64 value.
  53. type StandardGauge struct {
  54. value int64
  55. }
  56. // Snapshot returns a read-only copy of the gauge.
  57. func (g *StandardGauge) Snapshot() Gauge {
  58. return GaugeSnapshot(g.Value())
  59. }
  60. // Update updates the gauge's value.
  61. func (g *StandardGauge) Update(v int64) {
  62. atomic.StoreInt64(&g.value, v)
  63. }
  64. // Value returns the gauge's current value.
  65. func (g *StandardGauge) Value() int64 {
  66. return atomic.LoadInt64(&g.value)
  67. }