This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
metrics.go
80 lines (66 loc) · 2.16 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package util
import (
"context"
"fmt"
"time"
"github.com/flyteorg/flytestdlib/logger"
"github.com/flyteorg/flytestdlib/promutils"
"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc/codes"
)
const maxGRPCStatusCode = 17 // From _maxCode in "google.golang.org/grpc/codes"
type responseCodeMetrics struct {
scope promutils.Scope
responseCodeCounters map[codes.Code]prometheus.Counter
}
// RequestMetrics per-endpoint request metrics.
type RequestMetrics struct {
scope promutils.Scope
requestDuration promutils.StopWatch
errCount prometheus.Counter
successCount prometheus.Counter
responseCodes responseCodeMetrics
}
func (m *RequestMetrics) Time(fn func()) {
m.requestDuration.Time(fn)
}
func (m *RequestMetrics) Record(code codes.Code) {
if code == codes.OK {
m.successCount.Inc()
} else {
m.errCount.Inc()
}
counter, ok := m.responseCodes.responseCodeCounters[code]
if !ok {
logger.Warnf(context.TODO(), "encountered unexpected error code [%s]", code.String())
return
}
counter.Inc()
}
func (m *RequestMetrics) Success() {
m.Record(codes.OK)
}
func newResponseCodeMetrics(scope promutils.Scope) responseCodeMetrics {
responseCodeCounters := make(map[codes.Code]prometheus.Counter)
for i := 0; i < maxGRPCStatusCode; i++ {
code := codes.Code(i)
responseCodeCounters[code] = scope.MustNewCounter(code.String(),
fmt.Sprintf("count of responses returning: %s", code.String()))
}
return responseCodeMetrics{
scope: scope,
responseCodeCounters: responseCodeCounters,
}
}
func NewRequestMetrics(scope promutils.Scope, method string) RequestMetrics {
methodScope := scope.NewSubScope(method)
responseCodeMetrics := newResponseCodeMetrics(methodScope.NewSubScope("codes"))
return RequestMetrics{
scope: methodScope,
requestDuration: methodScope.MustNewStopWatch("duration",
"recorded response time duration for endpoint", time.Millisecond),
errCount: methodScope.MustNewCounter("errors", "count of errors returned by endpoint"),
successCount: methodScope.MustNewCounter("success", "count of successful responses returned by endpoint"),
responseCodes: responseCodeMetrics,
}
}