/
hook.go
75 lines (67 loc) · 2.2 KB
/
hook.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
package otredis
import (
"context"
"github.com/opentracing/opentracing-go/ext"
"github.com/opentracing/opentracing-go/log"
"strconv"
"strings"
"github.com/go-redis/redis/v7"
"github.com/opentracing/opentracing-go"
)
// reference: https://github.com/opentracing/specification/blob/master/semantic_conventions.md
type hook struct {
addrs []string
database int
}
// BeforeProcess is a hook before process.
func (h hook) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error) {
span, newCtx := opentracing.StartSpanFromContext(ctx, "redis:cmd")
ext.DBType.Set(span, "redis")
ext.DBInstance.Set(span, strconv.Itoa(h.database))
ext.PeerAddress.Set(span, strings.Join(h.addrs, ", "))
ext.PeerService.Set(span, "redis")
ext.SpanKind.Set(span, ext.SpanKindEnum("client"))
ext.DBStatement.Set(span, strings.ToUpper(cmd.Name()))
return newCtx, nil
}
// AfterProcess is a hook after process.
func (h hook) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
span := opentracing.SpanFromContext(ctx)
if span != nil {
// if context is raised an error.
if ctx.Err() != nil {
ext.Error.Set(span, true)
span.LogFields(log.Error(ctx.Err()))
}
span.Finish()
}
return nil
}
// BeforeProcessPipeline is a hook before pipeline process.
func (h hook) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error) {
span, newCtx := opentracing.StartSpanFromContext(ctx, "redis:pipeline:cmd")
ext.DBType.Set(span, "redis")
ext.DBInstance.Set(span, strconv.Itoa(h.database))
ext.PeerAddress.Set(span, strings.Join(h.addrs, ", "))
ext.PeerService.Set(span, "redis")
ext.SpanKind.Set(span, ext.SpanKindEnum("client"))
merge := make([]string, len(cmds))
for i, cmd := range cmds {
merge[i] = strings.ToUpper(cmd.Name())
}
ext.DBStatement.Set(span, strings.Join(merge, " --> "))
return newCtx, nil
}
// BeforeProcessPipeline is a hook after pipeline process.
func (h hook) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error {
span := opentracing.SpanFromContext(ctx)
if span != nil {
// if context is raised an error.
if ctx.Err() != nil {
ext.Error.Set(span, true)
span.LogFields(log.Error(ctx.Err()))
}
span.Finish()
}
return nil
}