gauge_float64.go 2.3 KB

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