1
0

histogram.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package metric
  2. import (
  3. prom "github.com/prometheus/client_golang/prometheus"
  4. "github.com/wuntsong-org/go-zero-plus/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. ConstLabels map[string]string
  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. // ObserveFloat allow to observe float64 values.
  22. ObserveFloat(v float64, labels ...string)
  23. close() bool
  24. }
  25. promHistogramVec struct {
  26. histogram *prom.HistogramVec
  27. }
  28. )
  29. // NewHistogramVec returns a HistogramVec.
  30. func NewHistogramVec(cfg *HistogramVecOpts) HistogramVec {
  31. if cfg == nil {
  32. return nil
  33. }
  34. vec := prom.NewHistogramVec(prom.HistogramOpts{
  35. Namespace: cfg.Namespace,
  36. Subsystem: cfg.Subsystem,
  37. Name: cfg.Name,
  38. Help: cfg.Help,
  39. Buckets: cfg.Buckets,
  40. ConstLabels: cfg.ConstLabels,
  41. }, cfg.Labels)
  42. prom.MustRegister(vec)
  43. hv := &promHistogramVec{
  44. histogram: vec,
  45. }
  46. proc.AddShutdownListener(func() {
  47. hv.close()
  48. })
  49. return hv
  50. }
  51. func (hv *promHistogramVec) Observe(v int64, labels ...string) {
  52. update(func() {
  53. hv.histogram.WithLabelValues(labels...).Observe(float64(v))
  54. })
  55. }
  56. func (hv *promHistogramVec) ObserveFloat(v float64, labels ...string) {
  57. update(func() {
  58. hv.histogram.WithLabelValues(labels...).Observe(v)
  59. })
  60. }
  61. func (hv *promHistogramVec) close() bool {
  62. return prom.Unregister(hv.histogram)
  63. }