-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathopentelemetry.js
More file actions
328 lines (288 loc) · 9.58 KB
/
opentelemetry.js
File metadata and controls
328 lines (288 loc) · 9.58 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
* Copyright (c) 2025, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {trace, context, SpanStatusCode} from '@opentelemetry/api'
import {hrTimeToMilliseconds, hrTimeToTimeStamp} from '@opentelemetry/core'
import logger from './logger-instance'
const DEFAULT_SERVICE_NAME = 'pwa-kit-react-sdk'
export const OTEL_CONFIG = {
serviceName: process.env.OTEL_SERVICE_NAME || DEFAULT_SERVICE_NAME,
enabled: process.env.OTEL_SDK_ENABLED === 'true',
b3TracingEnabled: process.env.OTEL_B3_TRACING_ENABLED === 'true'
}
export const getServiceName = () => OTEL_CONFIG.serviceName
const logSpanData = (span, event = 'start', res = null) => {
const spanContext = span.spanContext()
const startTime = span.startTime
const endTime = event === 'start' ? startTime : span.endTime
const duration = event === 'start' ? 0 : hrTimeToMilliseconds(span.duration)
// Create the span data object that matches the expected format
const spanData = {
traceId: spanContext.traceId,
parentId: span.parentSpanId,
name: span.name,
id: spanContext.spanId,
kind: span.kind,
timestamp: hrTimeToTimeStamp(startTime),
duration: duration,
attributes: {
'service.name': getServiceName(),
...span.attributes,
event: event // Add event type to distinguish start/end
},
status: {code: event === 'start' ? SpanStatusCode.UNSET : SpanStatusCode.OK},
events: [],
links: [],
start_time: startTime,
end_time: endTime,
forwardTrace: OTEL_CONFIG.b3TracingEnabled
}
// Inject B3 headers into response if available
if (res && process.env.DISABLE_B3_TRACING !== 'true' && event === 'start') {
res.setHeader('x-b3-traceid', spanContext.traceId)
res.setHeader('x-b3-spanid', spanContext.spanId)
res.setHeader('x-b3-sampled', '1')
if (span.parentSpanId) {
res.setHeader('x-b3-parentspanid', span.parentSpanId)
}
}
// Only log if this is an end event or if it's a start event for a new span
if (event === 'end' || !Object.prototype.hasOwnProperty.call(span.attributes, 'event')) {
logger.info('OpenTelemetry span data', {
namespace: 'opentelemetry.logSpanData',
additionalProperties: spanData
})
}
}
/**
* Creates a new span with the given name and options
* @param {string} name - The name of the span
* @param {Object} options - Span options
* @returns {Span} The created span
*/
export const createSpan = (name, options = {}) => {
try {
const tracer = trace.getTracer(getServiceName())
// Create a new span with the current context
const span = tracer.startSpan(
name,
{
...options,
attributes: {
...options.attributes,
'service.name': getServiceName()
}
},
context.active()
)
// Set the new span as active
logSpanData(span, 'start')
return trace.setSpan(context.active(), span)
} catch (error) {
logger.error('Failed to create span', {
namespace: 'opentelemetry',
additionalProperties: {
spanName: name,
error: error.message
}
})
return null
}
}
/**
* Creates a child span with the given name and attributes
* @param {string} name - The name of the span
* @param {Object} attributes - The attributes to add to the span
* @returns {Span} The created span
*/
export const createChildSpan = (name, attributes = {}) => {
try {
const tracer = trace.getTracer(getServiceName())
const ctx = context.active()
const parentSpan = trace.getSpan(ctx)
// Don't create duplicate spans
if (parentSpan?.attributes?.performance_mark === name) {
return parentSpan
}
const {performance_mark, performance_detail, ...otherAttributes} = attributes
const spanAttributes = {
'service.name': getServiceName(),
...otherAttributes
}
if (performance_mark) {
spanAttributes['performance.mark'] = performance_mark
spanAttributes['performance.type'] = 'start'
spanAttributes['performance.detail'] =
typeof performance_detail === 'string'
? performance_detail
: JSON.stringify(performance_detail)
}
const span = tracer.startSpan(
name,
{
attributes: spanAttributes
},
parentSpan ? ctx : undefined
)
logSpanData(span, 'start')
return span
} catch (error) {
logger.error('Error creating OpenTelemetry span', {
namespace: 'opentelemetry',
additionalProperties: {
spanName: name,
error: error.message,
stack: error.stack
}
})
return null
}
}
/**
* Ends a span and logs its data
* @param {Span} span - The span to end
*/
export const endSpan = (span) => {
if (!span) {
return
}
try {
span.end()
// Log completion data
logSpanData(span, 'end')
} catch (error) {
logger.error('Error ending OpenTelemetry span', {
namespace: 'opentelemetry',
additionalProperties: {
error: error.message,
stack: error.stack
}
})
}
}
/**
* Creates a span for performance measurement
* @param {string} name - The name of the performance span
* @param {Function} fn - The function to measure
* @param {Object} res - The response object (optional)
* @returns {Promise<any>} The result of the function
*/
export const tracePerformance = async (name, fn, res = null) => {
const tracer = trace.getTracer(getServiceName())
// Create the root span
const rootSpan = tracer.startSpan(name, {
attributes: {
'service.name': getServiceName()
}
})
// Create a new context with the root span
const ctx = trace.setSpan(context.active(), rootSpan)
// Log start event
logSpanData(rootSpan, 'start', res)
try {
// Run the function within the context of the root span
const result = await context.with(ctx, async () => {
try {
return await fn()
} catch (error) {
rootSpan.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
})
throw error
}
})
rootSpan.end()
// Log completion data
logSpanData(rootSpan, 'end', res)
return result
} catch (error) {
rootSpan.end()
// Log error completion
logSpanData(rootSpan, 'end', res)
throw error
}
}
/**
* Traces a performance metric
* @param {string} name - The name of the metric
* @param {number} duration - The duration of the metric in milliseconds
* @param {Object} attributes - Additional attributes for the metric
*/
export const logPerformanceMetric = (name, duration, attributes = {}) => {
try {
const tracer = trace.getTracer(getServiceName())
const ctx = context.active()
const parentSpan = trace.getSpan(ctx)
if (!parentSpan) {
logger.warn('No parent span found in context', {
namespace: 'opentelemetry',
additionalProperties: {metricName: name}
})
return
}
// Extract and normalize performance details
const {performance_mark, performance_detail, ...otherAttributes} = attributes
// Build metric attributes
const metricAttributes = {
'service.name': getServiceName(),
'metric.duration': duration,
...otherAttributes
}
if (performance_mark) {
metricAttributes['performance.mark'] = performance_mark
metricAttributes['performance.type'] = 'end'
metricAttributes['performance.detail'] =
typeof performance_detail === 'string'
? performance_detail
: JSON.stringify(performance_detail)
}
// Create and immediately end the metric span
const span = tracer.startSpan(
name,
{
attributes: metricAttributes
},
ctx
)
span.end()
// Log completion data
logSpanData(span, 'end')
} catch (error) {
logger.error('Error logging performance metric', {
namespace: 'opentelemetry',
additionalProperties: {
metricName: name,
error: error.message,
stack: error.stack
}
})
}
}
/**
* Traces a performance operation
* @param {string} name - The name of the operation
* @param {Function} fn - The function to trace
* @returns {Promise<any>} The result of the function
*/
export const traceChildPerformance = async (name, fn) => {
const span = createChildSpan(name)
if (!span) {
return fn()
}
try {
const result = await fn()
endSpan(span)
return result
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
})
endSpan(span)
throw error
}
}