/
metrics.go
106 lines (98 loc) · 2.62 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package metrics
import (
"context"
"strconv"
"time"
"github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/metrics"
"github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/transport"
)
// Option is metrics option.
type Option func(*options)
// WithRequests with requests counter.
func WithRequests(c metrics.Counter) Option {
return func(o *options) {
o.requests = c
}
}
// WithSeconds with seconds histogram.
func WithSeconds(c metrics.Observer) Option {
return func(o *options) {
o.seconds = c
}
}
type options struct {
// counter: <client/server>_requests_code_total{kind, operation, code, reason}
requests metrics.Counter
// histogram: <client/server>_requests_seconds_bucket{kind, operation}
seconds metrics.Observer
}
// Server is middleware server-side metrics.
func Server(opts ...Option) middleware.Middleware {
options := options{}
for _, o := range opts {
o(&options)
}
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (interface{}, error) {
var (
code int
reason string
kind string
operation string
)
startTime := time.Now()
if info, ok := transport.FromServerContext(ctx); ok {
kind = info.Kind().String()
operation = info.Operation()
}
reply, err := handler(ctx, req)
if se := errors.FromError(err); se != nil {
code = int(se.Code)
reason = se.Reason
}
if options.requests != nil {
options.requests.With(kind, operation, strconv.Itoa(code), reason).Inc()
}
if options.seconds != nil {
options.seconds.With(kind, operation).Observe(time.Since(startTime).Seconds())
}
return reply, err
}
}
}
// Client is middleware client-side metrics.
func Client(opts ...Option) middleware.Middleware {
options := options{}
for _, o := range opts {
o(&options)
}
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (interface{}, error) {
var (
code int
reason string
kind string
operation string
)
startTime := time.Now()
if info, ok := transport.FromClientContext(ctx); ok {
kind = info.Kind().String()
operation = info.Operation()
}
reply, err := handler(ctx, req)
if se := errors.FromError(err); se != nil {
code = int(se.Code)
reason = se.Reason
}
if options.requests != nil {
options.requests.With(kind, operation, strconv.Itoa(code), reason).Inc()
}
if options.seconds != nil {
options.seconds.With(kind, operation).Observe(time.Since(startTime).Seconds())
}
return reply, err
}
}
}