-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtracer.go
68 lines (54 loc) · 1.53 KB
/
tracer.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
package pgxxray
import (
"context"
"fmt"
"github.com/aws/aws-xray-sdk-go/xray"
"github.com/jackc/pgx/v5"
)
type segmentContextKey string
const xraySegmentKey segmentContextKey = "xray_segment"
type TraceType string
const (
BatchTraceType TraceType = "batch"
ConnectTraceType TraceType = "connect"
CopyFromTraceType TraceType = "copy_from"
PrepareTraceType TraceType = "prepare"
QueryTraceType TraceType = "query"
)
type PGXTracer struct {
traceEnabled map[TraceType]bool
}
func (t *PGXTracer) beginSubsegment(ctx context.Context, cfg *pgx.ConnConfig, prefix string) (context.Context, *xray.Segment) {
ctx, seg := xray.BeginSubsegment(ctx, t.segmentName(cfg, prefix))
return context.WithValue(ctx, xraySegmentKey, seg), seg
}
func (t *PGXTracer) segmentName(cfg *pgx.ConnConfig, prefix string) string {
return fmt.Sprintf("%s-%s/%s", prefix, cfg.Host, cfg.Database)
}
func (t *PGXTracer) tryGetSegment(ctx context.Context) *xray.Segment {
segRaw := ctx.Value(xraySegmentKey)
if segRaw != nil {
seg, ok := segRaw.(*xray.Segment)
if ok {
return seg
}
}
return nil
}
func NewPGXTracer(traceTypes ...TraceType) *PGXTracer {
traceEnabled := map[TraceType]bool{}
if len(traceTypes) == 0 {
traceEnabled[BatchTraceType] = true
traceEnabled[ConnectTraceType] = true
traceEnabled[CopyFromTraceType] = true
traceEnabled[PrepareTraceType] = true
traceEnabled[QueryTraceType] = true
} else {
for _, typ := range traceTypes {
traceEnabled[typ] = true
}
}
return &PGXTracer{
traceEnabled: traceEnabled,
}
}