-
Notifications
You must be signed in to change notification settings - Fork 2
/
tracing.go
90 lines (65 loc) · 2.02 KB
/
tracing.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
82
83
84
85
86
87
88
89
90
package pq
import (
"context"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/opentracing/opentracing-go/log"
)
const (
operationNameExec = "pq.Exec"
operationNameQuery = "pq.Query"
operationNameQueryRow = "pq.QueryRow"
operationNameTransaction = "pq.Transaction"
errLogKeyEvent = "event"
errLogKeyMessage = "message"
errLogValueErr = "error"
)
type tracingAdapter struct {
Transactor
Executor
}
var _ Client = &tracingAdapter{}
func (ta *tracingAdapter) Transaction(ctx context.Context, f func(context.Context, Executor) error) error {
span, spanCtx := opentracing.StartSpanFromContext(ctx, operationNameTransaction)
err := ta.Transactor.Transaction(spanCtx, f)
if err != nil {
traceErr(err, span)
}
span.Finish()
return err
}
func (ta *tracingAdapter) Exec(ctx context.Context, sql string, args ...interface{}) (result RowsAffected, err error) {
span, spanCtx := startSpan(ctx, operationNameExec)
rowsAffected, err := ta.Executor.Exec(spanCtx, sql, args...)
if err != nil {
traceErr(err, span)
}
span.Finish()
return rowsAffected, err
}
func (ta *tracingAdapter) Query(ctx context.Context, sql string, args ...interface{}) (Rows, error) {
span, spanCtx := startSpan(ctx, operationNameQuery)
rows, err := ta.Executor.Query(spanCtx, sql, args...)
if err != nil {
traceErr(err, span)
}
span.Finish()
return rows, err
}
func (ta *tracingAdapter) QueryRow(ctx context.Context, sql string, args ...interface{}) Row {
span, spanCtx := startSpan(ctx, operationNameQueryRow)
row := ta.Executor.QueryRow(spanCtx, sql, args...)
span.Finish()
return row
}
func traceErr(err error, span opentracing.Span) {
ext.Error.Set(span, true)
span.LogFields(
log.String(errLogKeyEvent, errLogValueErr),
log.String(errLogKeyMessage, err.Error()),
)
}
func startSpan(ctx context.Context, name string) (opentracing.Span, context.Context) {
span, spanCtx := opentracing.StartSpanFromContext(ctx, name)
return span, spanCtx
}