-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
120 lines (103 loc) · 2.57 KB
/
context.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package heldiamgo
import (
opentracinglog "github.com/opentracing/opentracing-go/log"
)
type IContext interface {
TracingContext
Copy() IContext
SetTracingType(int)
Logf(fields ...opentracinglog.Field) IContext
TracingSpan() TracingSpan
}
//上下文
type Context struct {
tracing TracingSpan //追踪数据
tracingType int //追踪类型[1=ChildOf,2=FollowsFrom]
//tracingStart bool //todo:是否可以通过是否开启追踪来复用一个对象..问题点:多个复用同时开启怎么处理
}
//ChildOf
func ContextChild(parentCtx IContext) IContext {
if parentCtx == nil {
return NewContext("ContextChild")
}
if Tracing && parentCtx.TracingSpan() != nil {
ret := parentCtx.Copy()
ret.SetTracingType(TracingChild)
return ret
}
return parentCtx
}
//FollowsFrom
func ContextFollows(parentCtx IContext) IContext {
if parentCtx == nil {
return NewContext("ContextFollows")
}
if Tracing && parentCtx.TracingSpan() != nil {
ret := parentCtx.Copy()
ret.SetTracingType(TracingFollowsFrom)
return ret
}
return parentCtx
}
//Copy
func (t *Context) Copy() IContext {
return &Context{
tracing: t.tracing,
tracingType: t.tracingType,
}
}
func (t *Context) SetTracingType(tracingType int) {
t.tracingType = tracingType
}
//Finish
func (t *Context) Finish() {
if t.tracing != nil {
t.tracing.Finish()
}
}
//日志
func (t *Context) Logf(fields ...opentracinglog.Field) IContext {
if t.tracing != nil && Tracing {
t.tracing.Logf(fields...)
}
return t
}
//追踪信息获取,可能返回nil
func (t *Context) TracingSpan() TracingSpan {
return t.tracing
}
//Start
func (t *Context) Start(operationName string) TracingContext {
//t.tracingStart = true
if Tracing {
if t.tracing == nil || t.tracing.Span() == nil { //没有父级span,生成根span
t.tracing = NewTracingSpanStart(operationName)
} else { //有父级span的按类型延伸子级,如果类型为空的不处理
switch t.tracingType {
case TracingChild:
t.tracing = t.tracing.ChildOf(operationName)
case TracingFollowsFrom:
t.tracing = t.tracing.FollowsFrom(operationName)
}
}
}
t.tracingType = 0 //清空追踪类型,往后传递没有指定类型时按之前值往下扩展
return t
}
//初始化上下文
func NewContext(operationName string) *Context {
ctx := &Context{}
if operationName != "" && Tracing {
ctx.tracing = NewTracingSpanStart(operationName)
}
return ctx
}
//初始化上下文
func NewContextWithTracing(tracingSpan TracingSpan) *Context {
if !Tracing {
tracingSpan = nil
}
return &Context{
tracing: tracingSpan,
}
}