gauge.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 VectorOpts
  8. GuageVec interface {
  9. Set(v float64, labels ...string)
  10. Inc(labels ...string)
  11. Add(v float64, labels ...string)
  12. close() bool
  13. }
  14. promGuageVec struct {
  15. gauge *prom.GaugeVec
  16. }
  17. )
  18. func NewGaugeVec(cfg *GaugeVecOpts) GuageVec {
  19. if cfg == nil {
  20. return nil
  21. }
  22. vec := prom.NewGaugeVec(
  23. prom.GaugeOpts{
  24. Namespace: cfg.Namespace,
  25. Subsystem: cfg.Subsystem,
  26. Name: cfg.Name,
  27. Help: cfg.Help,
  28. }, cfg.Labels)
  29. prom.MustRegister(vec)
  30. gv := &promGuageVec{
  31. gauge: vec,
  32. }
  33. proc.AddShutdownListener(func() {
  34. gv.close()
  35. })
  36. return gv
  37. }
  38. func (gv *promGuageVec) Inc(labels ...string) {
  39. gv.gauge.WithLabelValues(labels...).Inc()
  40. }
  41. func (gv *promGuageVec) Add(v float64, lables ...string) {
  42. gv.gauge.WithLabelValues(lables...).Add(v)
  43. }
  44. func (gv *promGuageVec) Set(v float64, lables ...string) {
  45. gv.gauge.WithLabelValues(lables...).Set(v)
  46. }
  47. func (gv *promGuageVec) close() bool {
  48. return prom.Unregister(gv.gauge)
  49. }