histogram.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 HistogramVecOpts is a histogram vector options.
  9. HistogramVecOpts struct {
  10. Namespace string
  11. Subsystem string
  12. Name string
  13. Help string
  14. Labels []string
  15. Buckets []float64
  16. }
  17. // A HistogramVec interface represents a histogram vector.
  18. HistogramVec interface {
  19. // Observe adds observation v to labels.
  20. Observe(v int64, labels ...string)
  21. close() bool
  22. }
  23. promHistogramVec struct {
  24. histogram *prom.HistogramVec
  25. }
  26. )
  27. // NewHistogramVec returns a HistogramVec.
  28. func NewHistogramVec(cfg *HistogramVecOpts) HistogramVec {
  29. if cfg == nil {
  30. return nil
  31. }
  32. vec := prom.NewHistogramVec(prom.HistogramOpts{
  33. Namespace: cfg.Namespace,
  34. Subsystem: cfg.Subsystem,
  35. Name: cfg.Name,
  36. Help: cfg.Help,
  37. Buckets: cfg.Buckets,
  38. }, cfg.Labels)
  39. prom.MustRegister(vec)
  40. hv := &promHistogramVec{
  41. histogram: vec,
  42. }
  43. proc.AddShutdownListener(func() {
  44. hv.close()
  45. })
  46. return hv
  47. }
  48. func (hv *promHistogramVec) Observe(v int64, labels ...string) {
  49. if !prometheus.Enabled() {
  50. return
  51. }
  52. hv.histogram.WithLabelValues(labels...).Observe(float64(v))
  53. }
  54. func (hv *promHistogramVec) close() bool {
  55. return prom.Unregister(hv.histogram)
  56. }