gauge.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package metric
  2. import (
  3. prom "github.com/prometheus/client_golang/prometheus"
  4. "github.com/wuntsong-org/go-zero-plus/core/proc"
  5. )
  6. type (
  7. // GaugeVecOpts is an alias of VectorOpts.
  8. GaugeVecOpts VectorOpts
  9. // GaugeVec represents a gauge vector.
  10. GaugeVec interface {
  11. // Set sets v to labels.
  12. Set(v float64, labels ...string)
  13. // Inc increments labels.
  14. Inc(labels ...string)
  15. // Dec decrements labels.
  16. Dec(labels ...string)
  17. // Add adds v to labels.
  18. Add(v float64, labels ...string)
  19. // Sub subtracts v to labels.
  20. Sub(v float64, labels ...string)
  21. close() bool
  22. }
  23. promGaugeVec struct {
  24. gauge *prom.GaugeVec
  25. }
  26. )
  27. // NewGaugeVec returns a GaugeVec.
  28. func NewGaugeVec(cfg *GaugeVecOpts) GaugeVec {
  29. if cfg == nil {
  30. return nil
  31. }
  32. vec := prom.NewGaugeVec(prom.GaugeOpts{
  33. Namespace: cfg.Namespace,
  34. Subsystem: cfg.Subsystem,
  35. Name: cfg.Name,
  36. Help: cfg.Help,
  37. }, cfg.Labels)
  38. prom.MustRegister(vec)
  39. gv := &promGaugeVec{
  40. gauge: vec,
  41. }
  42. proc.AddShutdownListener(func() {
  43. gv.close()
  44. })
  45. return gv
  46. }
  47. func (gv *promGaugeVec) Add(v float64, labels ...string) {
  48. update(func() {
  49. gv.gauge.WithLabelValues(labels...).Add(v)
  50. })
  51. }
  52. func (gv *promGaugeVec) Dec(labels ...string) {
  53. update(func() {
  54. gv.gauge.WithLabelValues(labels...).Dec()
  55. })
  56. }
  57. func (gv *promGaugeVec) Inc(labels ...string) {
  58. update(func() {
  59. gv.gauge.WithLabelValues(labels...).Inc()
  60. })
  61. }
  62. func (gv *promGaugeVec) Set(v float64, labels ...string) {
  63. update(func() {
  64. gv.gauge.WithLabelValues(labels...).Set(v)
  65. })
  66. }
  67. func (gv *promGaugeVec) Sub(v float64, labels ...string) {
  68. update(func() {
  69. gv.gauge.WithLabelValues(labels...).Sub(v)
  70. })
  71. }
  72. func (gv *promGaugeVec) close() bool {
  73. return prom.Unregister(gv.gauge)
  74. }