/
ctx.go
104 lines (91 loc) · 2.61 KB
/
ctx.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Copyright (C) 2014 Space Monkey, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package trace
import (
"fmt"
"golang.org/x/net/context"
)
type ctxKey int
const (
spanKey ctxKey = iota
)
type spanCtx struct {
span *Span
context.Context
}
func (s *spanCtx) Value(key interface{}) interface{} {
if key == spanKey {
return s
}
return s.Context.Value(key)
}
func (s *spanCtx) String() string {
if s.span.TraceDisabled() {
return fmt.Sprintf("%v.WithDisabledSpan()", s.Context)
}
return fmt.Sprintf("%v.WithSpan(%#v)", s.Context, s.span.Export())
}
func getSpan(ctx context.Context) (s *Span, ctx_to_wrap context.Context) {
if s, ok := ctx.(*spanCtx); ok && s != nil {
return s.span, s.Context
}
if s, ok := ctx.Value(spanKey).(*spanCtx); ok && s != nil {
return s.span, ctx
}
return nil, ctx
}
// TraceWithSpanNamed is like Trace, except you get to pick the Span name.
func (m *SpanManager) TraceWithSpanNamed(
ctx *context.Context, name string) func(*error) {
parent, parent_ctx := getSpan(*ctx)
if parent == nil {
s := m.NewTrace(name)
new_ctx := &spanCtx{
span: s,
Context: *ctx}
*ctx = new_ctx
return s.Observe()
}
if parent.TraceDisabled() {
return func(*error) {}
}
s := parent.NewSpan(name)
*ctx = &spanCtx{
span: s,
Context: parent_ctx}
return s.Observe()
}
// Trace is a utility that allows you to automatically create a Span (or a
// brand new trace, if needed) that observes the current function scope, given
// a function call context. The name of the Span is pulled from the current
// function name. See the example for usage.
func (m *SpanManager) Trace(ctx *context.Context) func(*error) {
return m.TraceWithSpanNamed(ctx, CallerName())
}
// ContextWithSpan creates a new Context with the provided Span set as the
// current Span.
func ContextWithSpan(ctx context.Context, s *Span) context.Context {
if s == nil {
return ctx
}
return &spanCtx{
span: s,
Context: ctx}
}
// SpanFromContext loads the current span from the current Context if one
// exists
func SpanFromContext(ctx context.Context) (s *Span, ok bool) {
s, _ = getSpan(ctx)
return s, s != nil
}