-
Notifications
You must be signed in to change notification settings - Fork 649
/
metric_utils.go
68 lines (57 loc) · 1.82 KB
/
metric_utils.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
56
57
58
59
60
61
62
63
64
65
66
67
68
package metricutils
import (
"context"
"net/http"
"time"
"github.com/ava-labs/avalanchego/utils"
"github.com/ava-labs/avalanchego/utils/wrappers"
"github.com/gorilla/rpc/v2"
"github.com/prometheus/client_golang/prometheus"
)
type APIRequestMetrics interface {
InterceptAPIRequest(i *rpc.RequestInfo) *http.Request
AfterAPIRequest(i *rpc.RequestInfo)
Register(registerer prometheus.Registerer) error
}
type contextKey int
const requestTimestampKey contextKey = iota
type apiRequest struct {
requestDuration *prometheus.HistogramVec
requestErrors *prometheus.CounterVec
}
func NewAPIMetrics(namespace string) APIRequestMetrics {
return &apiRequest{
requestDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: namespace,
Name: "request_duration_ms",
Buckets: utils.MillisecondsHTTPBuckets,
}, []string{"method"}),
requestErrors: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace,
Name: "request_error_count",
}, []string{"method"}),
}
}
func (apr *apiRequest) Register(registerer prometheus.Registerer) error {
errs := wrappers.Errs{}
errs.Add(
registerer.Register(apr.requestDuration),
registerer.Register(apr.requestErrors),
)
return errs.Err
}
func (apr *apiRequest) InterceptAPIRequest(i *rpc.RequestInfo) *http.Request {
return i.Request.WithContext(context.WithValue(i.Request.Context(), requestTimestampKey, time.Now()))
}
func (apr *apiRequest) AfterAPIRequest(i *rpc.RequestInfo) {
timestamp := i.Request.Context().Value(requestTimestampKey)
timeCast, ok := timestamp.(time.Time)
if !ok {
return
}
totalTime := time.Since(timeCast)
apr.requestDuration.With(prometheus.Labels{"method": i.Method}).Observe(float64(totalTime.Milliseconds()))
if i.Error != nil {
apr.requestErrors.With(prometheus.Labels{"method": i.Method}).Inc()
}
}