-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimelog.go
82 lines (67 loc) · 1.66 KB
/
timelog.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
package timelog
import (
"context"
"fmt"
"time"
"github.com/opentracing/opentracing-go"
)
var WithOpenTracing = false
const tl_ctx_key = "tl_ctx_key"
// An information about an action and its internal actions.
// To create a context with it use the function Start().
type TlEntity struct {
start time.Time
finish time.Time
message interface{}
otSpan opentracing.Span
parent *TlEntity
children []*TlEntity
}
func (e *TlEntity) finishAll(t time.Time) {
if e.finish.IsZero() {
if WithOpenTracing {
e.otSpan.Finish()
}
e.finish = t
}
for _, child := range e.children {
child.finishAll(t)
}
}
// Starts measuring.
func Start(ctx context.Context, msg interface{}) context.Context {
tl := &TlEntity{
start: time.Now(),
message: msg,
}
if WithOpenTracing {
tl.otSpan, ctx = opentracing.StartSpanFromContext(ctx, fmt.Sprintf("%s", msg))
}
if ctxTl := ctx.Value(tl_ctx_key); ctxTl != nil {
tl.parent = ctxTl.(*TlEntity)
ctxTl.(*TlEntity).children = append(ctxTl.(*TlEntity).children, tl)
}
return context.WithValue(ctx, tl_ctx_key, tl)
}
// Finishes measuring.
func Finish(ctx context.Context) context.Context {
t := time.Now()
var parent *TlEntity
if ctxTl := ctx.Value(tl_ctx_key); ctxTl != nil {
ctxTl.(*TlEntity).finishAll(t)
parent = ctxTl.(*TlEntity).parent
}
if parent != nil {
return context.WithValue(ctx, tl_ctx_key, parent)
} else {
return context.WithValue(ctx, tl_ctx_key, nil)
}
}
// Returns a TimeLog entry from context.
// Returns nil if context does not containg *TlEntity.
func Get(ctx context.Context) *TlEntity {
if ctxTl := ctx.Value(tl_ctx_key); ctxTl != nil {
return ctxTl.(*TlEntity)
}
return nil
}