gauge.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. // GaugeVecOpts is an alias of VectorOpts.
  9. GaugeVecOpts VectorOpts
  10. // GaugeVec represents a gauge vector.
  11. GaugeVec interface {
  12. // Set sets v to labels.
  13. Set(v float64, labels ...string)
  14. // Inc increments labels.
  15. Inc(labels ...string)
  16. // Dec decrements labels.
  17. Dec(labels ...string)
  18. // Add adds v to labels.
  19. Add(v float64, labels ...string)
  20. // Sub subtracts v to labels.
  21. Sub(v float64, labels ...string)
  22. close() bool
  23. }
  24. promGaugeVec struct {
  25. gauge *prom.GaugeVec
  26. }
  27. )
  28. // NewGaugeVec returns a GaugeVec.
  29. func NewGaugeVec(cfg *GaugeVecOpts) GaugeVec {
  30. if cfg == nil {
  31. return nil
  32. }
  33. vec := prom.NewGaugeVec(
  34. prom.GaugeOpts{
  35. Namespace: cfg.Namespace,
  36. Subsystem: cfg.Subsystem,
  37. Name: cfg.Name,
  38. Help: cfg.Help,
  39. }, cfg.Labels)
  40. prom.MustRegister(vec)
  41. gv := &promGaugeVec{
  42. gauge: vec,
  43. }
  44. proc.AddShutdownListener(func() {
  45. gv.close()
  46. })
  47. return gv
  48. }
  49. func (gv *promGaugeVec) Set(v float64, labels ...string) {
  50. if !prometheus.Enabled() {
  51. return
  52. }
  53. gv.gauge.WithLabelValues(labels...).Set(v)
  54. }
  55. func (gv *promGaugeVec) Inc(labels ...string) {
  56. if !prometheus.Enabled() {
  57. return
  58. }
  59. gv.gauge.WithLabelValues(labels...).Inc()
  60. }
  61. func (gv *promGaugeVec) Dec(labels ...string) {
  62. if !prometheus.Enabled() {
  63. return
  64. }
  65. gv.gauge.WithLabelValues(labels...).Dec()
  66. }
  67. func (gv *promGaugeVec) Add(v float64, labels ...string) {
  68. if !prometheus.Enabled() {
  69. return
  70. }
  71. gv.gauge.WithLabelValues(labels...).Add(v)
  72. }
  73. func (gv *promGaugeVec) Sub(v float64, labels ...string) {
  74. if !prometheus.Enabled() {
  75. return
  76. }
  77. gv.gauge.WithLabelValues(labels...).Sub(v)
  78. }
  79. func (gv *promGaugeVec) close() bool {
  80. return prom.Unregister(gv.gauge)
  81. }