gauge.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package metric
  2. import (
  3. "git.i2edu.net/i2/go-zero/core/proc"
  4. prom "github.com/prometheus/client_golang/prometheus"
  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. // Add adds v to labels.
  16. Add(v float64, labels ...string)
  17. close() bool
  18. }
  19. promGaugeVec struct {
  20. gauge *prom.GaugeVec
  21. }
  22. )
  23. // NewGaugeVec returns a GaugeVec.
  24. func NewGaugeVec(cfg *GaugeVecOpts) GaugeVec {
  25. if cfg == nil {
  26. return nil
  27. }
  28. vec := prom.NewGaugeVec(
  29. prom.GaugeOpts{
  30. Namespace: cfg.Namespace,
  31. Subsystem: cfg.Subsystem,
  32. Name: cfg.Name,
  33. Help: cfg.Help,
  34. }, cfg.Labels)
  35. prom.MustRegister(vec)
  36. gv := &promGaugeVec{
  37. gauge: vec,
  38. }
  39. proc.AddShutdownListener(func() {
  40. gv.close()
  41. })
  42. return gv
  43. }
  44. func (gv *promGaugeVec) Inc(labels ...string) {
  45. gv.gauge.WithLabelValues(labels...).Inc()
  46. }
  47. func (gv *promGaugeVec) Add(v float64, labels ...string) {
  48. gv.gauge.WithLabelValues(labels...).Add(v)
  49. }
  50. func (gv *promGaugeVec) Set(v float64, labels ...string) {
  51. gv.gauge.WithLabelValues(labels...).Set(v)
  52. }
  53. func (gv *promGaugeVec) close() bool {
  54. return prom.Unregister(gv.gauge)
  55. }