-
Notifications
You must be signed in to change notification settings - Fork 8
/
metrics.go
62 lines (46 loc) · 1.31 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
package decorator
import (
"context"
"fmt"
"strings"
"time"
)
type MetricsClient interface {
Inc(key string, value int)
}
type commandMetricsDecorator[C any] struct {
base CommandHandler[C]
client MetricsClient
}
func (d commandMetricsDecorator[C]) Handle(ctx context.Context, cmd C) (err error) {
start := time.Now()
actionName := strings.ToLower(generateActionName(cmd))
defer func() {
end := time.Since(start)
d.client.Inc(fmt.Sprintf("commands.%s.duration", actionName), int(end.Seconds()))
if err == nil {
d.client.Inc(fmt.Sprintf("commands.%s.success", actionName), 1)
} else {
d.client.Inc(fmt.Sprintf("commands.%s.failure", actionName), 1)
}
}()
return d.base.Handle(ctx, cmd)
}
type queryMetricsDecorator[C any, R any] struct {
base QueryHandler[C, R]
client MetricsClient
}
func (d queryMetricsDecorator[C, R]) Handle(ctx context.Context, query C) (result R, err error) {
start := time.Now()
actionName := strings.ToLower(generateActionName(query))
defer func() {
end := time.Since(start)
d.client.Inc(fmt.Sprintf("querys.%s.duration", actionName), int(end.Seconds()))
if err == nil {
d.client.Inc(fmt.Sprintf("querys.%s.success", actionName), 1)
} else {
d.client.Inc(fmt.Sprintf("querys.%s.failure", actionName), 1)
}
}()
return d.base.Handle(ctx, query)
}