| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package event |
| 6 |
|
| 7 |
import ( |
| 8 |
"context" |
| 9 |
"sync" |
| 10 |
"time" |
| 11 |
) |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
type Event struct { |
| 16 |
ID uint64 |
| 17 |
Parent uint64 |
| 18 |
Source Source |
| 19 |
At time.Time |
| 20 |
Kind Kind |
| 21 |
Labels []Label |
| 22 |
|
| 23 |
ctx context.Context |
| 24 |
target *target |
| 25 |
labels [preallocateLabels]Label |
| 26 |
} |
| 27 |
|
| 28 |
|
| 29 |
type Handler interface { |
| 30 |
|
| 31 |
Event(context.Context, *Event) context.Context |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
const preallocateLabels = 6 |
| 40 |
|
| 41 |
var eventPool = sync.Pool{New: func() interface{} { return &Event{} }} |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
func WithExporter(ctx context.Context, e *Exporter) context.Context { |
| 47 |
return newContext(ctx, e, 0, time.Time{}) |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
func SetDefaultExporter(e *Exporter) { |
| 53 |
setDefaultExporter(e) |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
func New(ctx context.Context, kind Kind) *Event { |
| 63 |
var t *target |
| 64 |
if v, ok := ctx.Value(contextKey).(*target); ok { |
| 65 |
t = v |
| 66 |
} else { |
| 67 |
t = getDefaultTarget() |
| 68 |
} |
| 69 |
if t == nil { |
| 70 |
return nil |
| 71 |
} |
| 72 |
|
| 73 |
switch kind { |
| 74 |
case LogKind: |
| 75 |
if !t.exporter.loggingEnabled() { |
| 76 |
return nil |
| 77 |
} |
| 78 |
case MetricKind: |
| 79 |
if !t.exporter.metricsEnabled() { |
| 80 |
return nil |
| 81 |
} |
| 82 |
case StartKind, EndKind: |
| 83 |
if !t.exporter.tracingEnabled() { |
| 84 |
return nil |
| 85 |
} |
| 86 |
} |
| 87 |
ev := eventPool.Get().(*Event) |
| 88 |
*ev = Event{ |
| 89 |
ctx: ctx, |
| 90 |
target: t, |
| 91 |
Kind: kind, |
| 92 |
Parent: t.parent, |
| 93 |
} |
| 94 |
ev.Labels = ev.labels[:0] |
| 95 |
return ev |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
func (ev *Event) Clone() *Event { |
| 101 |
ev2 := eventPool.Get().(*Event) |
| 102 |
*ev2 = *ev |
| 103 |
ev2.Labels = append(ev2.labels[:0], ev.Labels...) |
| 104 |
return ev2 |
| 105 |
} |
| 106 |
|
| 107 |
func (ev *Event) Trace() { |
| 108 |
ev.prepare() |
| 109 |
ev.ctx = newContext(ev.ctx, ev.target.exporter, ev.ID, ev.At) |
| 110 |
} |
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
func (ev *Event) Deliver() context.Context { |
| 116 |
|
| 117 |
ev.prepare() |
| 118 |
ctx := ev.deliver() |
| 119 |
eventPool.Put(ev) |
| 120 |
return ctx |
| 121 |
} |
| 122 |
|
| 123 |
func (ev *Event) deliver() context.Context { |
| 124 |
|
| 125 |
e := ev.target.exporter |
| 126 |
e.mu.Lock() |
| 127 |
defer e.mu.Unlock() |
| 128 |
return e.handler.Event(ev.ctx, ev) |
| 129 |
} |
| 130 |
|
| 131 |
func (ev *Event) Find(name string) Label { |
| 132 |
for _, l := range ev.Labels { |
| 133 |
if l.Name == name { |
| 134 |
return l |
| 135 |
} |
| 136 |
} |
| 137 |
return Label{} |
| 138 |
} |