base-golang/pkg/metrics/metrics.go
2024-07-23 10:23:43 +08:00

52 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package metrics
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/spf13/cast"
)
const (
namespace = "bvbej"
subsystem = "api"
)
// metricsRequestsTotal metrics for request total 计数器Counter
var metricsRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "requests_total",
Help: "request(ms) total",
},
[]string{"method", "path"},
)
// metricsRequestsCost metrics for requests cost 累积直方图Histogram
var metricsRequestsCost = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "requests_cost",
Help: "request(ms) cost milliseconds",
},
[]string{"method", "path", "success"},
)
func init() {
prometheus.MustRegister(metricsRequestsTotal, metricsRequestsCost)
}
// RecordMetrics 记录指标
func RecordMetrics(method, uri string, success bool, costSeconds float64) {
metricsRequestsTotal.With(prometheus.Labels{
"method": method,
"path": uri,
}).Inc()
metricsRequestsCost.With(prometheus.Labels{
"method": method,
"path": uri,
"success": cast.ToString(success),
}).Observe(costSeconds)
}