histogram.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package metric
  2. import (
  3. prom "github.com/prometheus/client_golang/prometheus"
  4. "github.com/zeromicro/go-zero/core/proc"
  5. )
  6. type (
  7. // A HistogramVecOpts is a histogram vector options.
  8. HistogramVecOpts struct {
  9. Namespace string
  10. Subsystem string
  11. Name string
  12. Help string
  13. Labels []string
  14. Buckets []float64
  15. }
  16. // A HistogramVec interface represents a histogram vector.
  17. HistogramVec interface {
  18. // Observe adds observation v to labels.
  19. Observe(v int64, labels ...string)
  20. close() bool
  21. }
  22. promHistogramVec struct {
  23. histogram *prom.HistogramVec
  24. }
  25. )
  26. // NewHistogramVec returns a HistogramVec.
  27. func NewHistogramVec(cfg *HistogramVecOpts) HistogramVec {
  28. if cfg == nil {
  29. return nil
  30. }
  31. vec := prom.NewHistogramVec(prom.HistogramOpts{
  32. Namespace: cfg.Namespace,
  33. Subsystem: cfg.Subsystem,
  34. Name: cfg.Name,
  35. Help: cfg.Help,
  36. Buckets: cfg.Buckets,
  37. }, cfg.Labels)
  38. prom.MustRegister(vec)
  39. hv := &promHistogramVec{
  40. histogram: vec,
  41. }
  42. proc.AddShutdownListener(func() {
  43. hv.close()
  44. })
  45. return hv
  46. }
  47. func (hv *promHistogramVec) Observe(v int64, labels ...string) {
  48. update(func() {
  49. hv.histogram.WithLabelValues(labels...).Observe(float64(v))
  50. })
  51. }
  52. func (hv *promHistogramVec) close() bool {
  53. return prom.Unregister(hv.histogram)
  54. }