/
monitor.go
78 lines (68 loc) · 2.29 KB
/
monitor.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
package client
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/go-bricks/bricks/v2/interfaces/http/client"
"github.com/go-bricks/bricks/v2/interfaces/monitor"
"go.uber.org/fx"
"google.golang.org/grpc"
)
// Names
const (
ClientTimerMetric = "client_calls_duration"
ClientTimerMetricDescription = "Monitor external HTTP client calls"
TargetTag = "target"
PathTag = "path"
SuccessTag = "success"
TypeTag = "ctype"
TypeGRPC = "grpc"
TypeREST = "rest"
)
type monitorDeps struct {
fx.In
Metrics monitor.Metrics `optional:"true"`
}
// MonitorGRPCClientCallsInterceptor create a new GRPC Unary Client interceptor that monitor all external client calls
func MonitorGRPCClientCallsInterceptor(deps monitorDeps) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) {
start := time.Now()
err = invoker(ctx, method, req, reply, cc, opts...)
if deps.Metrics != nil {
tags := prepareTags(cc.Target(), method, TypeGRPC, fmt.Sprintf("%t", err == nil))
deps.Metrics.
WithTags(tags).
Timer(ClientTimerMetric, ClientTimerMetricDescription).
WithContext(ctx).
Record(time.Since(start))
}
return
}
}
// MonitorRESTClientCallsInterceptor create a new REST Client interceptor that monitor all external client calls
func MonitorRESTClientCallsInterceptor(deps monitorDeps) client.HTTPClientInterceptor {
return func(req *http.Request, handler client.HTTPHandler) (resp *http.Response, err error) {
start := time.Now()
resp, err = handler(req)
if deps.Metrics != nil {
tags := prepareTags(req.Host, req.URL.Path, TypeREST, fmt.Sprintf("%t", err == nil && resp.StatusCode < http.StatusBadRequest))
deps.Metrics.
WithTags(tags).
Timer(ClientTimerMetric, ClientTimerMetricDescription).
WithContext(req.Context()).
Record(time.Since(start))
}
return
}
}
func prepareTags(host, path, clientType, err string) monitor.Tags {
host = strings.Trim(host, ":") // remove trailing port if exists
return monitor.Tags{
TargetTag: host,
PathTag: path,
SuccessTag: err,
TypeTag: clientType,
}
}