|
1
|
import { |
|
2
|
Tracer as OTTracer, |
|
3
|
Span, |
|
4
|
trace, |
|
5
|
context, |
|
6
|
propagation, |
|
7
|
} from "../deps/opentelemetry-api" |
|
8
|
|
|
9
|
/** |
|
10
|
* Tracer creates an instrumentation scope within the application |
|
11
|
* code. For example: You might create a tracer for the API |
|
12
|
* requests, another one for the modules, one for workflows |
|
13
|
* and so on. |
|
14
|
* |
|
15
|
* There is no need to create a Tracer instance per HTTP |
|
16
|
* call. |
|
17
|
*/ |
|
18
|
export class Tracer { |
|
19
|
/** |
|
20
|
* Reference to the underlying OpenTelemetry tracer |
|
21
|
*/ |
|
22
|
#otTracer: OTTracer |
|
23
|
constructor(public name: string, public version?: string) { |
|
24
|
this.#otTracer = trace.getTracer(name, version) |
|
25
|
} |
|
26
|
|
|
27
|
/** |
|
28
|
* Returns the underlying tracer from open telemetry that |
|
29
|
* could be used directly for certain advanced use-cases |
|
30
|
*/ |
|
31
|
getOTTracer() { |
|
32
|
return this.#otTracer |
|
33
|
} |
|
34
|
|
|
35
|
/** |
|
36
|
* Trace a function call. Using this method will create a |
|
37
|
* child scope for the invocations within the callback. |
|
38
|
*/ |
|
39
|
trace<F extends (span: Span) => unknown>( |
|
40
|
name: string, |
|
41
|
callback: F |
|
42
|
): ReturnType<F> { |
|
43
|
return this.#otTracer.startActiveSpan(name, callback) |
|
44
|
} |
|
45
|
|
|
46
|
/** |
|
47
|
* Returns the active context |
|
48
|
*/ |
|
49
|
getActiveContext() { |
|
50
|
return context.active() |
|
51
|
} |
|
52
|
|
|
53
|
/** |
|
54
|
* Returns the propagation state from the current active |
|
55
|
* context |
|
56
|
*/ |
|
57
|
getPropagationState() { |
|
58
|
let output = {} |
|
59
|
propagation.inject(context.active(), output) |
|
60
|
return output as { traceparent: string; tracestate?: string } |
|
61
|
} |
|
62
|
|
|
63
|
/** |
|
64
|
* Use the existing propogation state and trace an action. This |
|
65
|
* will allow the newly traced action to be part of some |
|
66
|
* existing trace |
|
67
|
*/ |
|
68
|
withPropagationState(state: { traceparent: string; tracestate?: string }) { |
|
69
|
return { |
|
70
|
trace: <F extends (span: Span) => unknown>( |
|
71
|
name: string, |
|
72
|
callback: F |
|
73
|
): ReturnType<F> => { |
|
74
|
const activeContext = propagation.extract(context.active(), state) |
|
75
|
return this.#otTracer.startActiveSpan(name, {}, activeContext, callback) |
|
76
|
}, |
|
77
|
} |
|
78
|
} |
|
79
|
} |