gauge.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. // Add adds v to labels.
  17. Add(v float64, labels ...string)
  18. close() bool
  19. }
  20. promGaugeVec struct {
  21. gauge *prom.GaugeVec
  22. }
  23. )
  24. // NewGaugeVec returns a GaugeVec.
  25. func NewGaugeVec(cfg *GaugeVecOpts) GaugeVec {
  26. if cfg == nil {
  27. return nil
  28. }
  29. vec := prom.NewGaugeVec(
  30. prom.GaugeOpts{
  31. Namespace: cfg.Namespace,
  32. Subsystem: cfg.Subsystem,
  33. Name: cfg.Name,
  34. Help: cfg.Help,
  35. }, cfg.Labels)
  36. prom.MustRegister(vec)
  37. gv := &promGaugeVec{
  38. gauge: vec,
  39. }
  40. proc.AddShutdownListener(func() {
  41. gv.close()
  42. })
  43. return gv
  44. }
  45. func (gv *promGaugeVec) Inc(labels ...string) {
  46. if !prometheus.Enabled() {
  47. return
  48. }
  49. gv.gauge.WithLabelValues(labels...).Inc()
  50. }
  51. func (gv *promGaugeVec) Add(v float64, labels ...string) {
  52. if !prometheus.Enabled() {
  53. return
  54. }
  55. gv.gauge.WithLabelValues(labels...).Add(v)
  56. }
  57. func (gv *promGaugeVec) Set(v float64, labels ...string) {
  58. if !prometheus.Enabled() {
  59. return
  60. }
  61. gv.gauge.WithLabelValues(labels...).Set(v)
  62. }
  63. func (gv *promGaugeVec) close() bool {
  64. return prom.Unregister(gv.gauge)
  65. }