/
mongo_tracing.go
67 lines (56 loc) · 1.96 KB
/
mongo_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
package mongo
import (
// Standard Library Imports
"context"
"fmt"
// External Imports
ot "github.com/opentracing/opentracing-go"
otExt "github.com/opentracing/opentracing-go/ext"
otLog "github.com/opentracing/opentracing-go/log"
)
type dbTrace struct {
// The Name of the struct who
Manager string
Method string
Selector interface{}
Query interface{}
CustomTags []ot.Tag
}
// traceMongoCall provides an abstraction from opentracing to obtain a span
// with relevant details when tracing call time to mongoDB
func traceMongoCall(ctx context.Context, trace dbTrace) (ot.Span, context.Context) {
// Build a new OpenTracing Child span to track how long it takes for mongo
// to complete the operation.
opName := fmt.Sprintf("storage.mongo.%s.%s", trace.Manager, trace.Method)
span, ctx := ot.StartSpanFromContext(ctx, opName)
// Tag component details
otExt.Component.Set(span, "storage")
otExt.DBType.Set(span, "mongo")
// Set the DB selector if provided.
// Generally useful for mongo updates where a selector is applied, then the
// payload supplied updates the given selected document. For example, the
// selector could end up selecting an inner document to be updated.
if trace.Selector != nil {
span.SetTag("DB.selector", fmt.Sprintf("%#+v", trace.Selector))
}
// Set the DB query if provided.
// Generally speaking, the query may not be needed, but may be helpful in
// debugging errors, therefore it is better advised to log the query out if
// an error occurs.
if trace.Query != nil {
otExt.DBStatement.Set(span, fmt.Sprintf("%#+v", trace.Query))
}
// Set the custom tags if provided
for _, tag := range trace.CustomTags {
tag.Set(span)
}
return span, ctx
}
// otLogQuery given a span and a query,
func otLogQuery(span ot.Span, query interface{}) {
otExt.DBStatement.Set(span, fmt.Sprintf("%#+v", query))
}
// otLogErr given a span, logs out the error
func otLogErr(span ot.Span, err error) {
span.LogFields(otLog.Error(err))
}