gauge.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package metrics
  2. import "github.com/prometheus/client_golang/prometheus"
  3. // Gauge is a metric that allows incrementing and decrementing a value
  4. type Gauge interface {
  5. Inc(...float64)
  6. Dec(...float64)
  7. // Add adds the provided value to the gauge's current value
  8. Add(float64)
  9. // Set replaces the gauge's current value with the provided value
  10. Set(float64)
  11. }
  12. // LabeledGauge describes a gauge the must have values populated before use.
  13. type LabeledGauge interface {
  14. WithValues(labels ...string) Gauge
  15. }
  16. type labeledGauge struct {
  17. pg *prometheus.GaugeVec
  18. }
  19. func (lg *labeledGauge) WithValues(labels ...string) Gauge {
  20. return &gauge{pg: lg.pg.WithLabelValues(labels...)}
  21. }
  22. func (lg *labeledGauge) Describe(c chan<- *prometheus.Desc) {
  23. lg.pg.Describe(c)
  24. }
  25. func (lg *labeledGauge) Collect(c chan<- prometheus.Metric) {
  26. lg.pg.Collect(c)
  27. }
  28. type gauge struct {
  29. pg prometheus.Gauge
  30. }
  31. func (g *gauge) Inc(vs ...float64) {
  32. if len(vs) == 0 {
  33. g.pg.Inc()
  34. }
  35. g.Add(sumFloat64(vs...))
  36. }
  37. func (g *gauge) Dec(vs ...float64) {
  38. if len(vs) == 0 {
  39. g.pg.Dec()
  40. }
  41. g.Add(-sumFloat64(vs...))
  42. }
  43. func (g *gauge) Add(v float64) {
  44. g.pg.Add(v)
  45. }
  46. func (g *gauge) Set(v float64) {
  47. g.pg.Set(v)
  48. }
  49. func (g *gauge) Describe(c chan<- *prometheus.Desc) {
  50. g.pg.Describe(c)
  51. }
  52. func (g *gauge) Collect(c chan<- prometheus.Metric) {
  53. g.pg.Collect(c)
  54. }