-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.go
55 lines (48 loc) · 1.52 KB
/
metrics.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package metrics
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/spf13/cast"
)
const (
namespace = "xhframwork"
subsystem = "xh_sys_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", "http_code", "business_code", "cost_milliseconds", "trace_id"},
)
func init() {
prometheus.MustRegister(metricsRequestsTotal, metricsRequestsCost)
}
// RecordMetrics 记录指标
func RecordMetrics(method, uri string, success bool, httpCode, businessCode int, costSeconds float64, traceId string) {
metricsRequestsTotal.With(prometheus.Labels{
"method": method,
"path": uri,
}).Inc()
metricsRequestsCost.With(prometheus.Labels{
"method": method,
"path": uri,
"success": cast.ToString(success),
"http_code": cast.ToString(httpCode),
"business_code": cast.ToString(businessCode),
"cost_milliseconds": cast.ToString(costSeconds * 1000),
"trace_id": traceId,
}).Observe(costSeconds)
}