counter.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. // 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) Inc(labels ...string) {
  42. cv.counter.WithLabelValues(labels...).Inc()
  43. }
  44. func (cv *promCounterVec) Add(v float64, labels ...string) {
  45. cv.counter.WithLabelValues(labels...).Add(v)
  46. }
  47. func (cv *promCounterVec) close() bool {
  48. return prom.Unregister(cv.counter)
  49. }