| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package event |
| 8 |
|
| 9 |
import ( |
| 10 |
"context" |
| 11 |
"sync" |
| 12 |
"sync/atomic" |
| 13 |
"time" |
| 14 |
"unsafe" |
| 15 |
) |
| 16 |
|
| 17 |
|
| 18 |
type Exporter struct { |
| 19 |
lastEvent uint64 |
| 20 |
opts ExporterOptions |
| 21 |
|
| 22 |
mu sync.Mutex |
| 23 |
handler Handler |
| 24 |
sources sources |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
type target struct { |
| 30 |
exporter *Exporter |
| 31 |
parent uint64 |
| 32 |
startTime time.Time |
| 33 |
} |
| 34 |
|
| 35 |
type ExporterOptions struct { |
| 36 |
|
| 37 |
Now func() time.Time |
| 38 |
|
| 39 |
|
| 40 |
DisableLogging bool |
| 41 |
DisableTracing bool |
| 42 |
DisableAnnotations bool |
| 43 |
DisableMetrics bool |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
EnableNamespaces bool |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
type contextKeyType struct{} |
| 52 |
|
| 53 |
var contextKey interface{} = contextKeyType{} |
| 54 |
|
| 55 |
var ( |
| 56 |
defaultTarget unsafe.Pointer |
| 57 |
) |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
func NewExporter(handler Handler, opts *ExporterOptions) *Exporter { |
| 62 |
if handler == nil { |
| 63 |
panic("handler must not be nil") |
| 64 |
} |
| 65 |
e := &Exporter{ |
| 66 |
handler: handler, |
| 67 |
sources: newCallers(), |
| 68 |
} |
| 69 |
if opts != nil { |
| 70 |
e.opts = *opts |
| 71 |
} |
| 72 |
if e.opts.Now == nil { |
| 73 |
e.opts.Now = time.Now |
| 74 |
} |
| 75 |
return e |
| 76 |
} |
| 77 |
|
| 78 |
func setDefaultExporter(e *Exporter) { |
| 79 |
atomic.StorePointer(&defaultTarget, unsafe.Pointer(&target{exporter: e})) |
| 80 |
} |
| 81 |
|
| 82 |
func getDefaultTarget() *target { |
| 83 |
return (*target)(atomic.LoadPointer(&defaultTarget)) |
| 84 |
} |
| 85 |
|
| 86 |
func newContext(ctx context.Context, exporter *Exporter, parent uint64, start time.Time) context.Context { |
| 87 |
var t *target |
| 88 |
if exporter != nil { |
| 89 |
t = &target{exporter: exporter, parent: parent, startTime: start} |
| 90 |
} |
| 91 |
return context.WithValue(ctx, contextKey, t) |
| 92 |
} |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
func (ev *Event) prepare() { |
| 101 |
e := ev.target.exporter |
| 102 |
if ev.ID == 0 { |
| 103 |
ev.ID = atomic.AddUint64(&e.lastEvent, 1) |
| 104 |
} |
| 105 |
if e.opts.Now != nil && ev.At.IsZero() { |
| 106 |
ev.At = e.opts.Now() |
| 107 |
} |
| 108 |
if e.opts.EnableNamespaces && ev.Source.Space == "" { |
| 109 |
ev.Source = e.sources.scanStack() |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
func (e *Exporter) loggingEnabled() bool { return !e.opts.DisableLogging } |
| 114 |
func (e *Exporter) annotationsEnabled() bool { return !e.opts.DisableAnnotations } |
| 115 |
func (e *Exporter) tracingEnabled() bool { return !e.opts.DisableTracing } |
| 116 |
func (e *Exporter) metricsEnabled() bool { return !e.opts.DisableMetrics } |