forked from DataDog/dd-trace-go
/
pg_go.go
70 lines (58 loc) · 1.85 KB
/
pg_go.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.
package pg
import (
"context"
"math"
"github.com/lannguyen-c0x12c/dd-trace-go/ddtrace"
"github.com/lannguyen-c0x12c/dd-trace-go/ddtrace/ext"
"github.com/lannguyen-c0x12c/dd-trace-go/ddtrace/tracer"
"github.com/lannguyen-c0x12c/dd-trace-go/internal/log"
"github.com/lannguyen-c0x12c/dd-trace-go/internal/telemetry"
"github.com/go-pg/pg/v10"
)
const componentName = "go-pg/pg.v10"
func init() {
telemetry.LoadIntegration(componentName)
}
// Wrap augments the given DB with tracing.
func Wrap(db *pg.DB, opts ...Option) {
cfg := new(config)
defaults(cfg)
for _, opt := range opts {
opt(cfg)
}
log.Debug("contrib/go-pg/pg.v10: Wrapping Database")
db.AddQueryHook(&queryHook{cfg: cfg})
}
type queryHook struct {
cfg *config
}
// BeforeQuery implements pg.QueryHook.
func (h *queryHook) BeforeQuery(ctx context.Context, qe *pg.QueryEvent) (context.Context, error) {
query, err := qe.UnformattedQuery()
if err != nil {
query = []byte("unknown")
}
opts := []ddtrace.StartSpanOption{
tracer.SpanType(ext.SpanTypeSQL),
tracer.ResourceName(string(query)),
tracer.ServiceName(h.cfg.serviceName),
tracer.Tag(ext.Component, componentName),
tracer.Tag(ext.DBSystem, ext.DBSystemPostgreSQL),
}
if !math.IsNaN(h.cfg.analyticsRate) {
opts = append(opts, tracer.Tag(ext.EventSampleRate, h.cfg.analyticsRate))
}
_, ctx = tracer.StartSpanFromContext(ctx, "go-pg", opts...)
return ctx, qe.Err
}
// AfterQuery implements pg.QueryHook
func (h *queryHook) AfterQuery(ctx context.Context, qe *pg.QueryEvent) error {
if span, ok := tracer.SpanFromContext(ctx); ok {
span.Finish(tracer.WithError(qe.Err))
}
return qe.Err
}