gauge.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package metric
  2. import (
  3. prom "github.com/prometheus/client_golang/prometheus"
  4. "github.com/tal-tech/go-zero/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. // Add adds v to labels.
  16. Add(v float64, labels ...string)
  17. close() bool
  18. }
  19. promGuageVec 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 := &promGuageVec{
  37. gauge: vec,
  38. }
  39. proc.AddShutdownListener(func() {
  40. gv.close()
  41. })
  42. return gv
  43. }
  44. func (gv *promGuageVec) Inc(labels ...string) {
  45. gv.gauge.WithLabelValues(labels...).Inc()
  46. }
  47. func (gv *promGuageVec) Add(v float64, lables ...string) {
  48. gv.gauge.WithLabelValues(lables...).Add(v)
  49. }
  50. func (gv *promGuageVec) Set(v float64, lables ...string) {
  51. gv.gauge.WithLabelValues(lables...).Set(v)
  52. }
  53. func (gv *promGuageVec) close() bool {
  54. return prom.Unregister(gv.gauge)
  55. }