histogram.go 1.0 KB

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