1 | import Tracer from './tracer';
|
2 |
|
3 | const noopTracer = new Tracer();
|
4 | let _globalTracer: Tracer | null = null;
|
5 |
|
6 | // Allows direct importing/requiring of the global tracer:
|
7 | //
|
8 | // let globalTracer = require('opentracing/global');
|
9 | // OR
|
10 | // import globalTracer from 'opentracing/global';
|
11 | //
|
12 | // Acts a bridge to the global tracer that can be safely called before the
|
13 | // global tracer is initialized. The purpose of the delegation is to avoid the
|
14 | // sometimes nearly intractible initialization order problems that can arise in
|
15 | // applications with a complex set of dependencies, while also avoiding the
|
16 | // case where
|
17 | class GlobalTracerDelegate extends Tracer {
|
18 |
|
19 | startSpan(): any {
|
20 | const tracer = _globalTracer || noopTracer;
|
21 | return tracer.startSpan.apply(tracer, arguments);
|
22 | }
|
23 |
|
24 | inject(): any {
|
25 | const tracer = _globalTracer || noopTracer;
|
26 | return tracer.inject.apply(tracer, arguments);
|
27 | }
|
28 |
|
29 | extract(): any {
|
30 | const tracer = _globalTracer || noopTracer;
|
31 | return tracer.extract.apply(tracer, arguments);
|
32 | }
|
33 | }
|
34 |
|
35 | const globalTracerDelegate = new GlobalTracerDelegate();
|
36 |
|
37 | /**
|
38 | * Set the global Tracer.
|
39 | *
|
40 | * The behavior is undefined if this function is called more than once.
|
41 | *
|
42 | * @param {Tracer} tracer - the Tracer implementation
|
43 | */
|
44 | export function initGlobalTracer(tracer: Tracer): void {
|
45 | _globalTracer = tracer;
|
46 | }
|
47 |
|
48 | /**
|
49 | * Returns the global tracer.
|
50 | */
|
51 | export function globalTracer(): Tracer {
|
52 | // Return the delegate. Since the global tracer is largely a convenience
|
53 | // (the user can always create their own tracers), the delegate is used to
|
54 | // give the added convenience of not needing to worry about initialization
|
55 | // order.
|
56 | return globalTracerDelegate;
|
57 | }
|