gauge.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // includes code from
  2. // https://raw.githubusercontent.com/rcrowley/go-metrics/master/sample.go
  3. // Copyright 2012 Richard Crowley. All rights reserved.
  4. package metrics
  5. import "sync/atomic"
  6. // Gauges hold an int64 value that can be set arbitrarily.
  7. type Gauge interface {
  8. Metric
  9. Update(int64)
  10. Value() int64
  11. }
  12. func NewGauge(meta *MetricMeta) Gauge {
  13. if UseNilMetrics {
  14. return NilGauge{}
  15. }
  16. return &StandardGauge{
  17. MetricMeta: meta,
  18. value: 0,
  19. }
  20. }
  21. func RegGauge(meta *MetricMeta) Gauge {
  22. g := NewGauge(meta)
  23. MetricStats.Register(g)
  24. return g
  25. }
  26. // GaugeSnapshot is a read-only copy of another Gauge.
  27. type GaugeSnapshot struct {
  28. *MetricMeta
  29. value int64
  30. }
  31. // Snapshot returns the snapshot.
  32. func (g GaugeSnapshot) Snapshot() Metric { return g }
  33. // Update panics.
  34. func (GaugeSnapshot) Update(int64) {
  35. panic("Update called on a GaugeSnapshot")
  36. }
  37. // Value returns the value at the time the snapshot was taken.
  38. func (g GaugeSnapshot) Value() int64 { return g.value }
  39. // NilGauge is a no-op Gauge.
  40. type NilGauge struct{ *MetricMeta }
  41. // Snapshot is a no-op.
  42. func (NilGauge) Snapshot() Metric { return NilGauge{} }
  43. // Update is a no-op.
  44. func (NilGauge) Update(v int64) {}
  45. // Value is a no-op.
  46. func (NilGauge) Value() int64 { return 0 }
  47. // StandardGauge is the standard implementation of a Gauge and uses the
  48. // sync/atomic package to manage a single int64 value.
  49. type StandardGauge struct {
  50. *MetricMeta
  51. value int64
  52. }
  53. // Snapshot returns a read-only copy of the gauge.
  54. func (g *StandardGauge) Snapshot() Metric {
  55. return GaugeSnapshot{MetricMeta: g.MetricMeta, value: g.value}
  56. }
  57. // Update updates the gauge's value.
  58. func (g *StandardGauge) Update(v int64) {
  59. atomic.StoreInt64(&g.value, v)
  60. }
  61. // Value returns the gauge's current value.
  62. func (g *StandardGauge) Value() int64 {
  63. return atomic.LoadInt64(&g.value)
  64. }