gauge.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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(name string, tagStrings ...string) Gauge {
  22. tr := NewGauge(NewMetricMeta(name, tagStrings))
  23. MetricStats.Register(tr)
  24. return tr
  25. }
  26. // GaugeSnapshot is a read-only copy of another Gauge.
  27. type GaugeSnapshot struct {
  28. value int64
  29. *MetricMeta
  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. // atomic needs 64-bit aligned memory which is ensure for first word
  50. type StandardGauge struct {
  51. value int64
  52. *MetricMeta
  53. }
  54. // Snapshot returns a read-only copy of the gauge.
  55. func (g *StandardGauge) Snapshot() Metric {
  56. return GaugeSnapshot{MetricMeta: g.MetricMeta, value: g.value}
  57. }
  58. // Update updates the gauge's value.
  59. func (g *StandardGauge) Update(v int64) {
  60. atomic.StoreInt64(&g.value, v)
  61. }
  62. // Value returns the gauge's current value.
  63. func (g *StandardGauge) Value() int64 {
  64. return atomic.LoadInt64(&g.value)
  65. }