counter.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package metric
  2. import (
  3. prom "github.com/prometheus/client_golang/prometheus"
  4. "github.com/zeromicro/go-zero/core/proc"
  5. "github.com/zeromicro/go-zero/core/prometheus"
  6. )
  7. type (
  8. // A CounterVecOpts is an alias of VectorOpts.
  9. CounterVecOpts VectorOpts
  10. // CounterVec interface represents a counter vector.
  11. CounterVec interface {
  12. // Inc increments labels.
  13. Inc(labels ...string)
  14. // Add adds labels with v.
  15. Add(v float64, labels ...string)
  16. close() bool
  17. }
  18. promCounterVec struct {
  19. counter *prom.CounterVec
  20. }
  21. )
  22. // NewCounterVec returns a CounterVec.
  23. func NewCounterVec(cfg *CounterVecOpts) CounterVec {
  24. if cfg == nil {
  25. return nil
  26. }
  27. vec := prom.NewCounterVec(prom.CounterOpts{
  28. Namespace: cfg.Namespace,
  29. Subsystem: cfg.Subsystem,
  30. Name: cfg.Name,
  31. Help: cfg.Help,
  32. }, cfg.Labels)
  33. prom.MustRegister(vec)
  34. cv := &promCounterVec{
  35. counter: vec,
  36. }
  37. proc.AddShutdownListener(func() {
  38. cv.close()
  39. })
  40. return cv
  41. }
  42. func (cv *promCounterVec) Inc(labels ...string) {
  43. if !prometheus.Enabled() {
  44. return
  45. }
  46. cv.counter.WithLabelValues(labels...).Inc()
  47. }
  48. func (cv *promCounterVec) Add(v float64, labels ...string) {
  49. if !prometheus.Enabled() {
  50. return
  51. }
  52. cv.counter.WithLabelValues(labels...).Add(v)
  53. }
  54. func (cv *promCounterVec) close() bool {
  55. return prom.Unregister(cv.counter)
  56. }