counter.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package metrics
  2. import (
  3. "strings"
  4. "sync/atomic"
  5. "github.com/prometheus/client_golang/prometheus"
  6. )
  7. // Counters hold an int64 value that can be incremented and decremented.
  8. type Counter interface {
  9. Metric
  10. Clear()
  11. Count() int64
  12. Inc(int64)
  13. }
  14. func promifyName(name string) string {
  15. return strings.Replace(name, ".", "_", -1)
  16. }
  17. // NewCounter constructs a new StandardCounter.
  18. func NewCounter(meta *MetricMeta) Counter {
  19. promCounter := prometheus.NewCounter(prometheus.CounterOpts{
  20. Name: promifyName(meta.Name()) + "_total",
  21. Help: meta.Name(),
  22. ConstLabels: prometheus.Labels(meta.GetTagsCopy()),
  23. })
  24. prometheus.MustRegister(promCounter)
  25. return &StandardCounter{
  26. MetricMeta: meta,
  27. count: 0,
  28. Counter: promCounter,
  29. }
  30. }
  31. func RegCounter(name string, tagStrings ...string) Counter {
  32. cr := NewCounter(NewMetricMeta(name, tagStrings))
  33. //MetricStats.Register(cr)
  34. return cr
  35. }
  36. // StandardCounter is the standard implementation of a Counter and uses the
  37. // sync/atomic package to manage a single int64 value.
  38. type StandardCounter struct {
  39. count int64 //Due to a bug in golang the 64bit variable need to come first to be 64bit aligned. https://golang.org/pkg/sync/atomic/#pkg-note-BUG
  40. *MetricMeta
  41. prometheus.Counter
  42. }
  43. // Clear sets the counter to zero.
  44. func (c *StandardCounter) Clear() {
  45. atomic.StoreInt64(&c.count, 0)
  46. }
  47. // Count returns the current count.
  48. func (c *StandardCounter) Count() int64 {
  49. return atomic.LoadInt64(&c.count)
  50. }
  51. // Dec decrements the counter by the given amount.
  52. func (c *StandardCounter) Dec(i int64) {
  53. atomic.AddInt64(&c.count, -i)
  54. }
  55. // Inc increments the counter by the given amount.
  56. func (c *StandardCounter) Inc(i int64) {
  57. atomic.AddInt64(&c.count, i)
  58. c.Counter.Add(float64(i))
  59. }
  60. func (c *StandardCounter) Snapshot() Metric {
  61. return &StandardCounter{
  62. MetricMeta: c.MetricMeta,
  63. count: c.count,
  64. }
  65. }