histogram.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package metric
  2. import (
  3. "git.i2edu.net/i2/go-zero/core/proc"
  4. prom "github.com/prometheus/client_golang/prometheus"
  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. hv.histogram.WithLabelValues(labels...).Observe(float64(v))
  49. }
  50. func (hv *promHistogramVec) close() bool {
  51. return prom.Unregister(hv.histogram)
  52. }