/
apptracer.go
76 lines (65 loc) · 1.7 KB
/
apptracer.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
package apptracer
import (
"golang.org/x/net/context"
"github.com/evalphobia/apptracer/platform"
)
// AppTracer has multiple tracing platform clients
// to send tracing activity to the platforms.
type AppTracer struct {
Config
ClientList []PlatformClient
}
// New returns initialized AppTracer.
func New(conf Config) *AppTracer {
return &AppTracer{
Config: conf,
}
}
// AddClient adds PlatformClient into ClientList.
func (a *AppTracer) AddClient(c PlatformClient) {
a.ClientList = append(a.ClientList, c)
}
// Trace creates *TraceWrapper from context.
// TraceWrapper contains platform clients and generates span data for the platforms.
// TraceWrapper is cached in the context and you can get same TraceWrapper
// when pass the same context.
func (a *AppTracer) Trace(ctx context.Context) *TraceWrapper {
switch {
case ctx == nil,
a == nil,
!a.Config.Enable:
return &TraceWrapper{}
}
t, ok := ctx.Value(traceKey{}).(*TraceWrapper)
if ok {
return t
}
t = &TraceWrapper{
traceList: make([]platform.Trace, 0, len(a.ClientList)),
defaultLabels: a.Config.DefaultLabels,
serviceName: a.Config.ServiceName,
version: a.Config.Version,
environment: a.Config.Environment,
}
for _, cli := range a.ClientList {
tr, err := cli.NewTrace(ctx)
if err == nil {
t.traceList = append(t.traceList, tr)
}
}
t.ctx = context.WithValue(ctx, traceKey{}, t)
return t
}
// Flush waits for exported data to be uploaded.
func (a *AppTracer) Flush() {
for _, cli := range a.ClientList {
cli.Flush()
}
}
// Close closes all of the clients.
func (a *AppTracer) Close() {
for _, cli := range a.ClientList {
cli.Close()
}
}
type traceKey struct{} // used to get TraceWrapper from context.