metrics.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package metrics
  2. import (
  3. "github.com/prometheus/client_golang/prometheus"
  4. "github.com/spf13/cast"
  5. )
  6. const (
  7. namespace = "bvbej"
  8. subsystem = "api"
  9. )
  10. // metricsRequestsTotal metrics for request total 计数器(Counter)
  11. var metricsRequestsTotal = prometheus.NewCounterVec(
  12. prometheus.CounterOpts{
  13. Namespace: namespace,
  14. Subsystem: subsystem,
  15. Name: "requests_total",
  16. Help: "request(ms) total",
  17. },
  18. []string{"method", "path"},
  19. )
  20. // metricsRequestsCost metrics for requests cost 累积直方图(Histogram)
  21. var metricsRequestsCost = prometheus.NewHistogramVec(
  22. prometheus.HistogramOpts{
  23. Namespace: namespace,
  24. Subsystem: subsystem,
  25. Name: "requests_cost",
  26. Help: "request(ms) cost milliseconds",
  27. },
  28. []string{"method", "path", "success"},
  29. )
  30. func init() {
  31. prometheus.MustRegister(metricsRequestsTotal, metricsRequestsCost)
  32. }
  33. // RecordMetrics 记录指标
  34. func RecordMetrics(method, uri string, success bool, costSeconds float64) {
  35. metricsRequestsTotal.With(prometheus.Labels{
  36. "method": method,
  37. "path": uri,
  38. }).Inc()
  39. metricsRequestsCost.With(prometheus.Labels{
  40. "method": method,
  41. "path": uri,
  42. "success": cast.ToString(success),
  43. }).Observe(costSeconds)
  44. }