counter.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. // A CounterVecOpts is an alias of VectorOpts.
  8. CounterVecOpts VectorOpts
  9. // CounterVec interface represents a counter vector.
  10. CounterVec interface {
  11. // Inc increments labels.
  12. Inc(labels ...string)
  13. // Add adds labels with v.
  14. Add(v float64, labels ...string)
  15. close() bool
  16. }
  17. promCounterVec struct {
  18. counter *prom.CounterVec
  19. }
  20. )
  21. // NewCounterVec returns a CounterVec.
  22. func NewCounterVec(cfg *CounterVecOpts) CounterVec {
  23. if cfg == nil {
  24. return nil
  25. }
  26. vec := prom.NewCounterVec(prom.CounterOpts{
  27. Namespace: cfg.Namespace,
  28. Subsystem: cfg.Subsystem,
  29. Name: cfg.Name,
  30. Help: cfg.Help,
  31. }, cfg.Labels)
  32. prom.MustRegister(vec)
  33. cv := &promCounterVec{
  34. counter: vec,
  35. }
  36. proc.AddShutdownListener(func() {
  37. cv.close()
  38. })
  39. return cv
  40. }
  41. func (cv *promCounterVec) Add(v float64, labels ...string) {
  42. update(func() {
  43. cv.counter.WithLabelValues(labels...).Add(v)
  44. })
  45. }
  46. func (cv *promCounterVec) Inc(labels ...string) {
  47. update(func() {
  48. cv.counter.WithLabelValues(labels...).Inc()
  49. })
  50. }
  51. func (cv *promCounterVec) close() bool {
  52. return prom.Unregister(cv.counter)
  53. }