-
Notifications
You must be signed in to change notification settings - Fork 2
/
metrics.go
60 lines (48 loc) · 1.72 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
package middleware
import (
"context"
"encoding/json"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/vmkteam/zenrpc/v2"
)
// WithMetrics logs duration of RPC requests via Prometheus. Default AppName is zenrpc. It exposes two
// metrics: `appName_rpc_error_requests_count` and `appName_rpc_responses_duration_seconds`. Labels: method, code,
// platform, version.
func WithMetrics(appName string) zenrpc.MiddlewareFunc {
if appName == "" {
appName = "zenrpc"
}
rpcErrors := prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: appName,
Subsystem: "rpc",
Name: "error_requests_count",
Help: "Error requests count by method and error code.",
}, []string{"method", "code", "platform", "version"})
rpcDurations := prometheus.NewSummaryVec(prometheus.SummaryOpts{
Namespace: appName,
Subsystem: "rpc",
Name: "responses_duration_seconds",
Help: "Response time by method and error code.",
}, []string{"method", "code", "platform", "version"})
prometheus.MustRegister(rpcErrors, rpcDurations)
return func(h zenrpc.InvokeFunc) zenrpc.InvokeFunc {
return func(ctx context.Context, method string, params json.RawMessage) zenrpc.Response {
start, code := time.Now(), ""
r := h(ctx, method, params)
// log metrics
if n := zenrpc.NamespaceFromContext(ctx); n != "" {
method = n + "." + method
}
// set platform & version
platform, version := PlatformFromContext(ctx), VersionFromContext(ctx)
if r.Error != nil {
code = strconv.Itoa(r.Error.Code)
rpcErrors.WithLabelValues(method, code, platform, version).Inc()
}
rpcDurations.WithLabelValues(method, code, platform, version).Observe(time.Since(start).Seconds())
return r
}
}
}