forked from qustavo/sqlhooks
/
othooks.go
53 lines (42 loc) · 1.1 KB
/
othooks.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
package othooks
import (
"context"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/log"
)
type Hook struct {
tracer opentracing.Tracer
}
func New(tracer opentracing.Tracer) *Hook {
return &Hook{tracer: tracer}
}
func (h *Hook) Before(ctx context.Context, query string, args ...interface{}) (context.Context, error) {
parent := opentracing.SpanFromContext(ctx)
if parent == nil {
return ctx, nil
}
span := h.tracer.StartSpan("sql", opentracing.ChildOf(parent.Context()))
span.LogFields(
log.String("query", query),
log.Object("args", args),
)
return opentracing.ContextWithSpan(ctx, span), nil
}
func (h *Hook) After(ctx context.Context, query string, args ...interface{}) (context.Context, error) {
span := opentracing.SpanFromContext(ctx)
if span != nil {
defer span.Finish()
}
return ctx, nil
}
func (h *Hook) OnError(ctx context.Context, err error, query string, args ...interface{}) error {
span := opentracing.SpanFromContext(ctx)
if span != nil {
defer span.Finish()
span.SetTag("error", true)
span.LogFields(
log.Error(err),
)
}
return err
}