-
Notifications
You must be signed in to change notification settings - Fork 663
/
metrics.go
81 lines (64 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
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0
//go:build !test
package api
import (
"context"
"time"
"github.com/absmach/magistrala/certs"
"github.com/go-kit/kit/metrics"
)
var _ certs.Service = (*metricsMiddleware)(nil)
type metricsMiddleware struct {
counter metrics.Counter
latency metrics.Histogram
svc certs.Service
}
// MetricsMiddleware instruments core service by tracking request count and latency.
func MetricsMiddleware(svc certs.Service, counter metrics.Counter, latency metrics.Histogram) certs.Service {
return &metricsMiddleware{
counter: counter,
latency: latency,
svc: svc,
}
}
// IssueCert instruments IssueCert method with metrics.
func (ms *metricsMiddleware) IssueCert(ctx context.Context, token, thingID, ttl string) (certs.Cert, error) {
defer func(begin time.Time) {
ms.counter.With("method", "issue_cert").Add(1)
ms.latency.With("method", "issue_cert").Observe(time.Since(begin).Seconds())
}(time.Now())
return ms.svc.IssueCert(ctx, token, thingID, ttl)
}
// ListCerts instruments ListCerts method with metrics.
func (ms *metricsMiddleware) ListCerts(ctx context.Context, token, thingID string, offset, limit uint64) (certs.Page, error) {
defer func(begin time.Time) {
ms.counter.With("method", "list_certs").Add(1)
ms.latency.With("method", "list_certs").Observe(time.Since(begin).Seconds())
}(time.Now())
return ms.svc.ListCerts(ctx, token, thingID, offset, limit)
}
// ListSerials instruments ListSerials method with metrics.
func (ms *metricsMiddleware) ListSerials(ctx context.Context, token, thingID string, offset, limit uint64) (certs.Page, error) {
defer func(begin time.Time) {
ms.counter.With("method", "list_serials").Add(1)
ms.latency.With("method", "list_serials").Observe(time.Since(begin).Seconds())
}(time.Now())
return ms.svc.ListSerials(ctx, token, thingID, offset, limit)
}
// ViewCert instruments ViewCert method with metrics.
func (ms *metricsMiddleware) ViewCert(ctx context.Context, token, serialID string) (certs.Cert, error) {
defer func(begin time.Time) {
ms.counter.With("method", "view_cert").Add(1)
ms.latency.With("method", "view_cert").Observe(time.Since(begin).Seconds())
}(time.Now())
return ms.svc.ViewCert(ctx, token, serialID)
}
// RevokeCert instruments RevokeCert method with metrics.
func (ms *metricsMiddleware) RevokeCert(ctx context.Context, token, thingID string) (certs.Revoke, error) {
defer func(begin time.Time) {
ms.counter.With("method", "revoke_cert").Add(1)
ms.latency.With("method", "revoke_cert").Observe(time.Since(begin).Seconds())
}(time.Now())
return ms.svc.RevokeCert(ctx, token, thingID)
}