@sebspark/otel 2.0.7 → 2.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +74 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +740 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +12 -12
- package/dist/index.d.ts +0 -69
- package/dist/index.js +0 -965
- package/dist/index.js.map +0 -1
package/dist/index.js
DELETED
|
@@ -1,965 +0,0 @@
|
|
|
1
|
-
// src/index.ts
|
|
2
|
-
import {
|
|
3
|
-
context as context4,
|
|
4
|
-
SpanStatusCode as SpanStatusCode4
|
|
5
|
-
} from "@opentelemetry/api";
|
|
6
|
-
|
|
7
|
-
// src/instrumentations.ts
|
|
8
|
-
var _http;
|
|
9
|
-
var _express;
|
|
10
|
-
var _grpc;
|
|
11
|
-
var _redis;
|
|
12
|
-
var _dns;
|
|
13
|
-
var _net;
|
|
14
|
-
var _fs;
|
|
15
|
-
var _undici;
|
|
16
|
-
var _socketIo;
|
|
17
|
-
var instrumentations = {
|
|
18
|
-
get http() {
|
|
19
|
-
if (!_http) {
|
|
20
|
-
_http = import("@opentelemetry/instrumentation-http").then(
|
|
21
|
-
({ HttpInstrumentation }) => new HttpInstrumentation()
|
|
22
|
-
);
|
|
23
|
-
}
|
|
24
|
-
return _http;
|
|
25
|
-
},
|
|
26
|
-
get express() {
|
|
27
|
-
if (!_express) {
|
|
28
|
-
_express = import("@opentelemetry/instrumentation-express").then(
|
|
29
|
-
({ ExpressInstrumentation }) => new ExpressInstrumentation()
|
|
30
|
-
);
|
|
31
|
-
}
|
|
32
|
-
return _express;
|
|
33
|
-
},
|
|
34
|
-
get grpc() {
|
|
35
|
-
if (!_grpc) {
|
|
36
|
-
_grpc = import("@opentelemetry/instrumentation-grpc").then(
|
|
37
|
-
({ GrpcInstrumentation }) => new GrpcInstrumentation()
|
|
38
|
-
);
|
|
39
|
-
}
|
|
40
|
-
return _grpc;
|
|
41
|
-
},
|
|
42
|
-
get redis() {
|
|
43
|
-
if (!_redis) {
|
|
44
|
-
_redis = import("@opentelemetry/instrumentation-redis").then(
|
|
45
|
-
({ RedisInstrumentation }) => new RedisInstrumentation()
|
|
46
|
-
);
|
|
47
|
-
}
|
|
48
|
-
return _redis;
|
|
49
|
-
},
|
|
50
|
-
get dns() {
|
|
51
|
-
if (!_dns) {
|
|
52
|
-
_dns = import("@opentelemetry/instrumentation-dns").then(
|
|
53
|
-
({ DnsInstrumentation }) => new DnsInstrumentation()
|
|
54
|
-
);
|
|
55
|
-
}
|
|
56
|
-
return _dns;
|
|
57
|
-
},
|
|
58
|
-
get net() {
|
|
59
|
-
if (!_net) {
|
|
60
|
-
_net = import("@opentelemetry/instrumentation-net").then(
|
|
61
|
-
({ NetInstrumentation }) => new NetInstrumentation()
|
|
62
|
-
);
|
|
63
|
-
}
|
|
64
|
-
return _net;
|
|
65
|
-
},
|
|
66
|
-
get fs() {
|
|
67
|
-
if (!_fs) {
|
|
68
|
-
_fs = import("@opentelemetry/instrumentation-fs").then(
|
|
69
|
-
({ FsInstrumentation }) => new FsInstrumentation()
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
return _fs;
|
|
73
|
-
},
|
|
74
|
-
get undici() {
|
|
75
|
-
if (!_undici) {
|
|
76
|
-
_undici = import("@opentelemetry/instrumentation-undici").then(
|
|
77
|
-
({ UndiciInstrumentation }) => new UndiciInstrumentation()
|
|
78
|
-
);
|
|
79
|
-
}
|
|
80
|
-
return _undici;
|
|
81
|
-
},
|
|
82
|
-
get socketIo() {
|
|
83
|
-
if (!_socketIo) {
|
|
84
|
-
_socketIo = import("@opentelemetry/instrumentation-socket.io").then(
|
|
85
|
-
({ SocketIoInstrumentation }) => new SocketIoInstrumentation()
|
|
86
|
-
);
|
|
87
|
-
}
|
|
88
|
-
return _socketIo;
|
|
89
|
-
}
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
// src/logger.ts
|
|
93
|
-
import { context as context2, trace as trace2 } from "@opentelemetry/api";
|
|
94
|
-
import { logs as logs2 } from "@opentelemetry/api-logs";
|
|
95
|
-
|
|
96
|
-
// src/consts.ts
|
|
97
|
-
var LOG_SEVERITY_MAP = {
|
|
98
|
-
TRACE: 1,
|
|
99
|
-
DEBUG: 5,
|
|
100
|
-
INFO: 9,
|
|
101
|
-
NOTICE: 10,
|
|
102
|
-
WARNING: 13,
|
|
103
|
-
WARN: 13,
|
|
104
|
-
ERROR: 17,
|
|
105
|
-
FATAL: 21,
|
|
106
|
-
CRITICAL: 21,
|
|
107
|
-
ALERT: 22,
|
|
108
|
-
EMERGENCY: 23
|
|
109
|
-
};
|
|
110
|
-
|
|
111
|
-
// src/otel.ts
|
|
112
|
-
import {
|
|
113
|
-
context,
|
|
114
|
-
DiagConsoleLogger,
|
|
115
|
-
DiagLogLevel,
|
|
116
|
-
diag,
|
|
117
|
-
metrics,
|
|
118
|
-
trace
|
|
119
|
-
} from "@opentelemetry/api";
|
|
120
|
-
import { logs } from "@opentelemetry/api-logs";
|
|
121
|
-
import { NodeSDK } from "@opentelemetry/sdk-node";
|
|
122
|
-
|
|
123
|
-
// src/providers.ts
|
|
124
|
-
import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
|
|
125
|
-
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
|
|
126
|
-
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
|
127
|
-
import {
|
|
128
|
-
BatchLogRecordProcessor,
|
|
129
|
-
LoggerProvider,
|
|
130
|
-
SimpleLogRecordProcessor
|
|
131
|
-
} from "@opentelemetry/sdk-logs";
|
|
132
|
-
import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
|
|
133
|
-
import {
|
|
134
|
-
BatchSpanProcessor
|
|
135
|
-
} from "@opentelemetry/sdk-trace-node";
|
|
136
|
-
|
|
137
|
-
// src/loggers/console-metric-pretty-exporter.ts
|
|
138
|
-
import { ExportResultCode } from "@opentelemetry/core";
|
|
139
|
-
|
|
140
|
-
// src/loggers/formatters/shared.ts
|
|
141
|
-
import {
|
|
142
|
-
ATTR_SERVICE_NAME,
|
|
143
|
-
ATTR_SERVICE_VERSION
|
|
144
|
-
} from "@opentelemetry/semantic-conventions";
|
|
145
|
-
import fss from "fast-safe-stringify";
|
|
146
|
-
|
|
147
|
-
// src/loggers/formatters/style.ts
|
|
148
|
-
import kleur from "kleur";
|
|
149
|
-
var colors = {
|
|
150
|
-
gray: kleur.gray,
|
|
151
|
-
dim: kleur.dim,
|
|
152
|
-
cyan: kleur.cyan,
|
|
153
|
-
white: kleur.white,
|
|
154
|
-
green: kleur.green,
|
|
155
|
-
yellow: kleur.yellow,
|
|
156
|
-
red: kleur.red,
|
|
157
|
-
magenta: kleur.magenta
|
|
158
|
-
};
|
|
159
|
-
var levelColorMap = {
|
|
160
|
-
DEBUG: kleur.magenta,
|
|
161
|
-
INFO: kleur.green,
|
|
162
|
-
WARN: kleur.yellow,
|
|
163
|
-
ERROR: kleur.red,
|
|
164
|
-
FATAL: kleur.red
|
|
165
|
-
};
|
|
166
|
-
var levelIconMap = {
|
|
167
|
-
DEBUG: "\u{1F41B}",
|
|
168
|
-
INFO: "\u2139\uFE0F ",
|
|
169
|
-
WARN: "\u26A0\uFE0F ",
|
|
170
|
-
ERROR: "\u274C",
|
|
171
|
-
FATAL: "\u{1F480}"
|
|
172
|
-
};
|
|
173
|
-
var statusLabelMap = {
|
|
174
|
-
0: "UNSET",
|
|
175
|
-
1: "OK",
|
|
176
|
-
2: "ERROR"
|
|
177
|
-
};
|
|
178
|
-
var statusColorMap = {
|
|
179
|
-
0: colors.gray,
|
|
180
|
-
// UNSET
|
|
181
|
-
1: colors.green,
|
|
182
|
-
// OK
|
|
183
|
-
2: colors.red
|
|
184
|
-
// ERROR
|
|
185
|
-
};
|
|
186
|
-
var kindColorMap = {
|
|
187
|
-
0: colors.white,
|
|
188
|
-
// INTERNAL
|
|
189
|
-
1: colors.cyan,
|
|
190
|
-
// SERVER
|
|
191
|
-
2: colors.yellow,
|
|
192
|
-
// CLIENT
|
|
193
|
-
3: colors.magenta,
|
|
194
|
-
// PRODUCER
|
|
195
|
-
4: colors.green
|
|
196
|
-
// CONSUMER
|
|
197
|
-
};
|
|
198
|
-
|
|
199
|
-
// src/loggers/formatters/shared.ts
|
|
200
|
-
var stringify = fss.default.stableStringify;
|
|
201
|
-
function formatTimestamp(time) {
|
|
202
|
-
const date = new Date(hrTimeToMillis(time));
|
|
203
|
-
return colors.dim(date.toISOString().slice(11, 23));
|
|
204
|
-
}
|
|
205
|
-
function formatService(resource) {
|
|
206
|
-
const name = resource.attributes[ATTR_SERVICE_NAME] ?? "unknown-service";
|
|
207
|
-
const version = resource.attributes[ATTR_SERVICE_VERSION] ?? "1.0.0";
|
|
208
|
-
return colors.gray(`[${name}@${version}]`);
|
|
209
|
-
}
|
|
210
|
-
function formatLevel(record) {
|
|
211
|
-
const text = (record.severityText ?? "INFO").toUpperCase();
|
|
212
|
-
const colorFn = levelColorMap[text] ?? colors.white;
|
|
213
|
-
const icon = levelIconMap[text] ?? "\u2022";
|
|
214
|
-
return `${icon} ${colorFn(text.padEnd(5))}`;
|
|
215
|
-
}
|
|
216
|
-
function formatScope(resource, instrumentationScope) {
|
|
217
|
-
const component = resource.attributes["component.name"];
|
|
218
|
-
const { name, version } = instrumentationScope;
|
|
219
|
-
const scopeLabel = component || (name && name !== "unknown" ? name : void 0);
|
|
220
|
-
if (!scopeLabel) return "";
|
|
221
|
-
const versionLabel = version ? `@${version}` : "";
|
|
222
|
-
return colors.cyan(`${scopeLabel}${versionLabel} `);
|
|
223
|
-
}
|
|
224
|
-
function formatMessage(record) {
|
|
225
|
-
return typeof record.body === "string" ? record.body : stringify(record.body);
|
|
226
|
-
}
|
|
227
|
-
function formatAttributes(attrs) {
|
|
228
|
-
const keys = Object.keys(attrs).filter(
|
|
229
|
-
(k) => !k.startsWith("service.") && !k.startsWith("serviceContext.")
|
|
230
|
-
);
|
|
231
|
-
if (keys.length === 0) return "";
|
|
232
|
-
const formatted = keys.map((k) => {
|
|
233
|
-
const val = attrs[k];
|
|
234
|
-
return `${k}=${typeof val === "object" ? stringify(val) : val}`;
|
|
235
|
-
});
|
|
236
|
-
return ` ${colors.gray(formatted.join(" "))}`;
|
|
237
|
-
}
|
|
238
|
-
function hrTimeToMillis(hrTime) {
|
|
239
|
-
return hrTime[0] * 1e3 + Math.floor(hrTime[1] / 1e6);
|
|
240
|
-
}
|
|
241
|
-
function calculateDuration(span) {
|
|
242
|
-
const start = hrTimeToMillis(span.startTime);
|
|
243
|
-
const end = hrTimeToMillis(span.endTime);
|
|
244
|
-
return Math.max(0, Math.round(end - start));
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
// src/loggers/formatters/log-record.ts
|
|
248
|
-
function formatLogRecord(record) {
|
|
249
|
-
const timestamp = formatTimestamp(record.hrTime);
|
|
250
|
-
const service = formatService(record.resource);
|
|
251
|
-
const level = formatLevel(record);
|
|
252
|
-
const scope = formatScope(record.resource, record.instrumentationScope);
|
|
253
|
-
const message = formatMessage(record);
|
|
254
|
-
const attrs = formatAttributes(record.attributes);
|
|
255
|
-
return `${service} ${timestamp} ${level} ${scope}${message}${attrs}`;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// src/loggers/formatters/metrics.ts
|
|
259
|
-
function formatMetrics(resourceMetrics) {
|
|
260
|
-
const { resource, scopeMetrics } = resourceMetrics;
|
|
261
|
-
return scopeMetrics.map((scopeMetric) => formatScopeMetric(scopeMetric, resource)).join("\n");
|
|
262
|
-
}
|
|
263
|
-
function formatScopeMetric(scopeMetric, resource) {
|
|
264
|
-
return scopeMetric.metrics.map(
|
|
265
|
-
(metric) => formatMetricData(metric, resource, scopeMetric.scope)
|
|
266
|
-
).join("\n");
|
|
267
|
-
}
|
|
268
|
-
function formatMetricData(metric, resource, scope) {
|
|
269
|
-
const scopeStr = formatScope(resource, scope);
|
|
270
|
-
const serviceStr = formatService(resource);
|
|
271
|
-
const lines = [];
|
|
272
|
-
for (const dp of metric.dataPoints) {
|
|
273
|
-
const ts = formatTimestamp(dp.startTime);
|
|
274
|
-
const value = extractMetricValue(dp);
|
|
275
|
-
const attrs = formatAttributes(dp.attributes ?? {});
|
|
276
|
-
lines.push(
|
|
277
|
-
`${serviceStr} ${ts} \u{1F4CA} ${scopeStr}${colors.white(metric.descriptor.name)} ${colors.dim(value)}${attrs}`
|
|
278
|
-
);
|
|
279
|
-
}
|
|
280
|
-
return lines.join("\n");
|
|
281
|
-
}
|
|
282
|
-
function extractMetricValue(dp) {
|
|
283
|
-
const value = dp.value;
|
|
284
|
-
if (typeof value === "number") {
|
|
285
|
-
return value.toString();
|
|
286
|
-
}
|
|
287
|
-
if (isHistogramLike(value)) {
|
|
288
|
-
return value.sum.toString();
|
|
289
|
-
}
|
|
290
|
-
return "[complex]";
|
|
291
|
-
}
|
|
292
|
-
function isHistogramLike(val) {
|
|
293
|
-
return typeof val === "object" && val !== null && "sum" in val && typeof val.sum === "number";
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
// src/loggers/formatters/span.ts
|
|
297
|
-
import { SpanStatusCode } from "@opentelemetry/api";
|
|
298
|
-
var LABEL_WIDTH = 20;
|
|
299
|
-
var DESCRIPTION_MAX_WIDTH = 16;
|
|
300
|
-
var BAR_MIN_WIDTH = 1;
|
|
301
|
-
var BAR_MAX_WIDTH = 20;
|
|
302
|
-
function formatSpans(spans) {
|
|
303
|
-
const rootSpan = spans[0];
|
|
304
|
-
const rootStart = hrTimeToMillis(rootSpan.startTime);
|
|
305
|
-
const rootEnd = hrTimeToMillis(rootSpan.endTime);
|
|
306
|
-
const totalDuration = rootEnd - rootStart;
|
|
307
|
-
const service = formatService(rootSpan.resource);
|
|
308
|
-
const timestamp = formatTimestamp(rootSpan.startTime);
|
|
309
|
-
const traceId = colors.gray(`[${rootSpan.spanContext().traceId}]`);
|
|
310
|
-
const lines = [`${service} ${timestamp} ${traceId}`];
|
|
311
|
-
for (const span of spans) {
|
|
312
|
-
const offset = hrTimeToMillis(span.startTime) - rootStart;
|
|
313
|
-
const depth = computeDepth(span, spans);
|
|
314
|
-
lines.push(
|
|
315
|
-
formatSpan(span, {
|
|
316
|
-
offsetMs: offset,
|
|
317
|
-
totalDurationMs: totalDuration,
|
|
318
|
-
depth
|
|
319
|
-
})
|
|
320
|
-
);
|
|
321
|
-
}
|
|
322
|
-
return lines.join("\n");
|
|
323
|
-
}
|
|
324
|
-
function formatSpan(span, opts) {
|
|
325
|
-
const label = formatLabel(span, opts.depth);
|
|
326
|
-
const bar = buildBar(span, opts?.offsetMs, opts?.totalDurationMs);
|
|
327
|
-
const barColor = span.status.code === SpanStatusCode.OK ? colors.green : span.status.code === SpanStatusCode.ERROR ? colors.red : colors.gray;
|
|
328
|
-
const desc = formatDescription(span);
|
|
329
|
-
const status = formatStatus(span);
|
|
330
|
-
const duration = formatDuration(span, opts?.offsetMs);
|
|
331
|
-
const spanId = colors.gray(`[${span.spanContext().spanId}]`);
|
|
332
|
-
return `${label} ${barColor(bar)} ${desc} ${status} ${duration} ${spanId}`;
|
|
333
|
-
}
|
|
334
|
-
function formatLabel(span, depth) {
|
|
335
|
-
const indent = " ".repeat(depth);
|
|
336
|
-
const label = `${indent}\u2514\u2500 ${span.name}`;
|
|
337
|
-
return label.padEnd(LABEL_WIDTH);
|
|
338
|
-
}
|
|
339
|
-
function buildBar(span, offsetMs, totalDurationMs) {
|
|
340
|
-
const duration = calculateDuration(span);
|
|
341
|
-
if (typeof offsetMs !== "number" || typeof totalDurationMs !== "number" || totalDurationMs === 0) {
|
|
342
|
-
const capped = Math.min(duration, 1e3);
|
|
343
|
-
const barLength = Math.max(
|
|
344
|
-
BAR_MIN_WIDTH,
|
|
345
|
-
Math.round(capped / 1e3 * BAR_MAX_WIDTH)
|
|
346
|
-
);
|
|
347
|
-
return "\u2588".repeat(barLength).padEnd(BAR_MAX_WIDTH + 2);
|
|
348
|
-
}
|
|
349
|
-
const offsetRatio = Math.max(0, Math.min(offsetMs / totalDurationMs, 1));
|
|
350
|
-
const durationRatio = Math.max(0, Math.min(duration / totalDurationMs, 1));
|
|
351
|
-
const offsetChars = Math.floor(offsetRatio * BAR_MAX_WIDTH);
|
|
352
|
-
const barChars = Math.max(
|
|
353
|
-
BAR_MIN_WIDTH,
|
|
354
|
-
Math.round(durationRatio * BAR_MAX_WIDTH)
|
|
355
|
-
);
|
|
356
|
-
const empty = " ".repeat(offsetChars);
|
|
357
|
-
const bar = "\u2588".repeat(barChars);
|
|
358
|
-
return (empty + bar).padEnd(BAR_MAX_WIDTH + 2);
|
|
359
|
-
}
|
|
360
|
-
function formatDescription(span) {
|
|
361
|
-
const keyPriority = [
|
|
362
|
-
// HTTP
|
|
363
|
-
["http.method", "http.target"],
|
|
364
|
-
// → GET /users/123
|
|
365
|
-
["http.route"],
|
|
366
|
-
// → /users/:id
|
|
367
|
-
["http.url"],
|
|
368
|
-
// → https://...
|
|
369
|
-
// GraphQL
|
|
370
|
-
["graphql.operation.name"],
|
|
371
|
-
// → getUsers
|
|
372
|
-
["graphql.operation.type"],
|
|
373
|
-
// → query
|
|
374
|
-
["graphql.document"],
|
|
375
|
-
// → full query text (maybe too long)
|
|
376
|
-
// WebSocket
|
|
377
|
-
["ws.event"],
|
|
378
|
-
// → connection, message, disconnect
|
|
379
|
-
["ws.message_type"],
|
|
380
|
-
// → ping/pong/text/binary
|
|
381
|
-
["ws.url"],
|
|
382
|
-
// → wss://...
|
|
383
|
-
// Redis
|
|
384
|
-
["db.system", "db.statement"],
|
|
385
|
-
// → redis, "SET foo bar"
|
|
386
|
-
["db.operation"],
|
|
387
|
-
// → GET, SET
|
|
388
|
-
// Spanner
|
|
389
|
-
["db.statement"],
|
|
390
|
-
// → SELECT * FROM...
|
|
391
|
-
["db.operation"],
|
|
392
|
-
// → SELECT, INSERT
|
|
393
|
-
["db.name"],
|
|
394
|
-
// → projects/.../instances/.../databases/...
|
|
395
|
-
// OpenSearch
|
|
396
|
-
["db.operation"],
|
|
397
|
-
// → search, index, bulk
|
|
398
|
-
["db.statement"],
|
|
399
|
-
// → { query DSL... }
|
|
400
|
-
// Pub/Sub (GCP)
|
|
401
|
-
["messaging.operation"],
|
|
402
|
-
// → publish, receive
|
|
403
|
-
["messaging.destination"],
|
|
404
|
-
// → topic-a
|
|
405
|
-
["messaging.gcp_pubsub.topic"],
|
|
406
|
-
// → projects/x/topics/y
|
|
407
|
-
// General FaaS
|
|
408
|
-
["faas.invoked_name"],
|
|
409
|
-
// → myFunction
|
|
410
|
-
["faas.trigger"],
|
|
411
|
-
// → http, pubsub, etc.
|
|
412
|
-
// Custom or fallback
|
|
413
|
-
["otel.description"]
|
|
414
|
-
];
|
|
415
|
-
for (const keys of keyPriority) {
|
|
416
|
-
const parts = keys.map((k) => span.attributes[k]).filter((v) => v !== void 0 && v !== null).map((v) => String(v));
|
|
417
|
-
if (parts.length > 0) {
|
|
418
|
-
return truncate(parts.join(" "), DESCRIPTION_MAX_WIDTH - 1).padEnd(
|
|
419
|
-
DESCRIPTION_MAX_WIDTH
|
|
420
|
-
);
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
return "".padEnd(DESCRIPTION_MAX_WIDTH);
|
|
424
|
-
}
|
|
425
|
-
function formatStatus(span) {
|
|
426
|
-
const code = span.status.code;
|
|
427
|
-
const label = statusLabelMap[code] ?? "UNSET";
|
|
428
|
-
const colorFn = statusColorMap[code] ?? colors.gray;
|
|
429
|
-
return colorFn(label).padEnd(6);
|
|
430
|
-
}
|
|
431
|
-
function formatDuration(span, offsetMs) {
|
|
432
|
-
const duration = calculateDuration(span);
|
|
433
|
-
const format = (ms) => ms >= 1e3 ? `${(ms / 1e3).toFixed(2)} s` : `${ms} ms`;
|
|
434
|
-
return `(${format(offsetMs || 0)}\u2013${format(duration)})`.padEnd(16);
|
|
435
|
-
}
|
|
436
|
-
function truncate(input, maxLength) {
|
|
437
|
-
const str = String(input ?? "");
|
|
438
|
-
return str.length > maxLength ? `${str.slice(0, maxLength - 1)}\u2026` : str;
|
|
439
|
-
}
|
|
440
|
-
function computeDepth(span, allSpans) {
|
|
441
|
-
let depth = 0;
|
|
442
|
-
let currentParentId = span.parentSpanContext?.spanId;
|
|
443
|
-
while (currentParentId) {
|
|
444
|
-
const parentSpan = allSpans.find(
|
|
445
|
-
(s) => s.spanContext().spanId === currentParentId
|
|
446
|
-
);
|
|
447
|
-
if (!parentSpan) break;
|
|
448
|
-
depth += 1;
|
|
449
|
-
currentParentId = parentSpan.parentSpanContext?.spanId;
|
|
450
|
-
}
|
|
451
|
-
return depth;
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
// src/loggers/console-metric-pretty-exporter.ts
|
|
455
|
-
var ConsoleMetricPrettyExporter = class {
|
|
456
|
-
patterns;
|
|
457
|
-
constructor() {
|
|
458
|
-
const raw = process.env.METRIC_FILTER ?? "";
|
|
459
|
-
const entries = raw.split(",").map((e) => e.trim()).filter(Boolean);
|
|
460
|
-
this.patterns = entries.map(globToRegex);
|
|
461
|
-
}
|
|
462
|
-
filterMetrics(resourceMetrics) {
|
|
463
|
-
if (this.patterns.length === 0) return void 0;
|
|
464
|
-
const filteredScopes = resourceMetrics.scopeMetrics.map((scopeMetric) => {
|
|
465
|
-
const filteredMetrics = scopeMetric.metrics.filter(
|
|
466
|
-
(metric) => this.patterns.some((pattern) => pattern.test(metric.descriptor.name))
|
|
467
|
-
);
|
|
468
|
-
if (filteredMetrics.length === 0) return void 0;
|
|
469
|
-
return {
|
|
470
|
-
...scopeMetric,
|
|
471
|
-
metrics: filteredMetrics
|
|
472
|
-
};
|
|
473
|
-
}).filter((s) => s !== void 0);
|
|
474
|
-
if (filteredScopes.length === 0) return void 0;
|
|
475
|
-
return {
|
|
476
|
-
...resourceMetrics,
|
|
477
|
-
scopeMetrics: filteredScopes
|
|
478
|
-
};
|
|
479
|
-
}
|
|
480
|
-
export(metrics3, resultCallback) {
|
|
481
|
-
const filtered = this.filterMetrics(metrics3);
|
|
482
|
-
if (filtered) {
|
|
483
|
-
console.log(formatMetrics(filtered));
|
|
484
|
-
}
|
|
485
|
-
resultCallback({ code: ExportResultCode.SUCCESS });
|
|
486
|
-
}
|
|
487
|
-
shutdown() {
|
|
488
|
-
return Promise.resolve();
|
|
489
|
-
}
|
|
490
|
-
forceFlush() {
|
|
491
|
-
return Promise.resolve();
|
|
492
|
-
}
|
|
493
|
-
};
|
|
494
|
-
function globToRegex(glob) {
|
|
495
|
-
const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
496
|
-
const regex = `^${escaped.replace(/\*/g, ".*")}$`;
|
|
497
|
-
return new RegExp(regex);
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
// src/loggers/console-log-pretty-exporter.ts
|
|
501
|
-
import { SeverityNumber } from "@opentelemetry/api-logs";
|
|
502
|
-
import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
|
|
503
|
-
var ConsoleLogPrettyExporter = class {
|
|
504
|
-
logThreshold;
|
|
505
|
-
constructor() {
|
|
506
|
-
const defaultLogLevel = "INFO";
|
|
507
|
-
const env = process.env.LOG_LEVEL?.toUpperCase() ?? defaultLogLevel;
|
|
508
|
-
this.logThreshold = LOG_SEVERITY_MAP[env] ?? LOG_SEVERITY_MAP[defaultLogLevel];
|
|
509
|
-
}
|
|
510
|
-
export(logs3, resultCallback) {
|
|
511
|
-
this._sendLogRecords(logs3, resultCallback);
|
|
512
|
-
}
|
|
513
|
-
shutdown() {
|
|
514
|
-
return Promise.resolve();
|
|
515
|
-
}
|
|
516
|
-
forceFlush() {
|
|
517
|
-
return Promise.resolve();
|
|
518
|
-
}
|
|
519
|
-
_sendLogRecords(logRecords, done) {
|
|
520
|
-
for (const record of logRecords) {
|
|
521
|
-
if ((record.severityNumber ?? 0) >= this.logThreshold) {
|
|
522
|
-
const formatted = formatLogRecord(record);
|
|
523
|
-
const severity = record.severityNumber || SeverityNumber.UNSPECIFIED;
|
|
524
|
-
if (severity >= SeverityNumber.ERROR) {
|
|
525
|
-
console.error(formatted);
|
|
526
|
-
} else if (severity >= SeverityNumber.WARN) {
|
|
527
|
-
console.warn(formatted);
|
|
528
|
-
} else if (severity >= SeverityNumber.INFO) {
|
|
529
|
-
console.info(formatted);
|
|
530
|
-
} else if (severity >= SeverityNumber.DEBUG) {
|
|
531
|
-
console.debug(formatted);
|
|
532
|
-
} else {
|
|
533
|
-
console.trace(formatted);
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
done?.({ code: ExportResultCode2.SUCCESS });
|
|
538
|
-
}
|
|
539
|
-
};
|
|
540
|
-
|
|
541
|
-
// src/loggers/console-span-pretty-exporter.ts
|
|
542
|
-
import { SpanStatusCode as SpanStatusCode2 } from "@opentelemetry/api";
|
|
543
|
-
import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
|
|
544
|
-
var ConsoleSpanPrettyExporter = class {
|
|
545
|
-
allowedStatuses;
|
|
546
|
-
constructor() {
|
|
547
|
-
const env = process.env.SPAN_LEVEL?.toUpperCase();
|
|
548
|
-
if (!env) {
|
|
549
|
-
this.allowedStatuses = /* @__PURE__ */ new Set([
|
|
550
|
-
SpanStatusCode2.UNSET,
|
|
551
|
-
SpanStatusCode2.OK,
|
|
552
|
-
SpanStatusCode2.ERROR
|
|
553
|
-
]);
|
|
554
|
-
} else {
|
|
555
|
-
const map = {
|
|
556
|
-
UNSET: SpanStatusCode2.UNSET,
|
|
557
|
-
OK: SpanStatusCode2.OK,
|
|
558
|
-
ERROR: SpanStatusCode2.ERROR
|
|
559
|
-
};
|
|
560
|
-
this.allowedStatuses = new Set(
|
|
561
|
-
env.split(",").map((s) => s.trim()).map((s) => map[s]).filter((v) => typeof v === "number")
|
|
562
|
-
);
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
shouldExport(spans) {
|
|
566
|
-
if (this.allowedStatuses.size === 3) {
|
|
567
|
-
return true;
|
|
568
|
-
}
|
|
569
|
-
return spans.some((span) => this.allowedStatuses.has(span.status.code));
|
|
570
|
-
}
|
|
571
|
-
export(spans, resultCallback) {
|
|
572
|
-
if (this.shouldExport(spans)) {
|
|
573
|
-
console.log(formatSpans(spans));
|
|
574
|
-
}
|
|
575
|
-
resultCallback({ code: ExportResultCode3.SUCCESS });
|
|
576
|
-
}
|
|
577
|
-
shutdown() {
|
|
578
|
-
return Promise.resolve();
|
|
579
|
-
}
|
|
580
|
-
};
|
|
581
|
-
|
|
582
|
-
// src/loggers/tree-span-processor.ts
|
|
583
|
-
var TreeSpanProcessor = class {
|
|
584
|
-
exporter;
|
|
585
|
-
orphans = /* @__PURE__ */ new Map();
|
|
586
|
-
constructor(exporter) {
|
|
587
|
-
this.exporter = exporter;
|
|
588
|
-
}
|
|
589
|
-
onStart() {
|
|
590
|
-
}
|
|
591
|
-
onEnd(span) {
|
|
592
|
-
const parentId = span.parentSpanContext?.spanId;
|
|
593
|
-
if (parentId) {
|
|
594
|
-
const siblings = this.orphans.get(parentId) || [];
|
|
595
|
-
this.orphans.set(parentId, [...siblings, span]);
|
|
596
|
-
return;
|
|
597
|
-
}
|
|
598
|
-
const children = this.getChildrenRecursively(span);
|
|
599
|
-
const sorted = [span, ...children].sort((s1, s2) => {
|
|
600
|
-
const [sec1, nano1] = s1.startTime;
|
|
601
|
-
const [sec2, nano2] = s2.startTime;
|
|
602
|
-
if (sec1 !== sec2) return sec1 - sec2;
|
|
603
|
-
return nano1 - nano2;
|
|
604
|
-
});
|
|
605
|
-
this.exporter.export(sorted, () => {
|
|
606
|
-
});
|
|
607
|
-
}
|
|
608
|
-
getChildrenRecursively(span) {
|
|
609
|
-
const spanId = span.spanContext().spanId;
|
|
610
|
-
const children = this.orphans.get(spanId) || [];
|
|
611
|
-
this.orphans.delete(spanId);
|
|
612
|
-
const result = [...children];
|
|
613
|
-
for (const child of children) {
|
|
614
|
-
result.push(...this.getChildrenRecursively(child));
|
|
615
|
-
}
|
|
616
|
-
return result;
|
|
617
|
-
}
|
|
618
|
-
shutdown() {
|
|
619
|
-
return this.exporter.shutdown();
|
|
620
|
-
}
|
|
621
|
-
async forceFlush() {
|
|
622
|
-
await this.exporter.forceFlush?.();
|
|
623
|
-
}
|
|
624
|
-
};
|
|
625
|
-
|
|
626
|
-
// src/providers.ts
|
|
627
|
-
var getLogProvider = (resource, otlpEndpoint) => {
|
|
628
|
-
if (otlpEndpoint) {
|
|
629
|
-
const exporter2 = new OTLPLogExporter({ url: `${otlpEndpoint}/v1/logs` });
|
|
630
|
-
const processors = [
|
|
631
|
-
new BatchLogRecordProcessor(exporter2)
|
|
632
|
-
];
|
|
633
|
-
if (process.env.LOG_LEVEL) {
|
|
634
|
-
processors.push(
|
|
635
|
-
new SimpleLogRecordProcessor(new ConsoleLogPrettyExporter())
|
|
636
|
-
);
|
|
637
|
-
}
|
|
638
|
-
return new LoggerProvider({
|
|
639
|
-
resource,
|
|
640
|
-
processors
|
|
641
|
-
});
|
|
642
|
-
}
|
|
643
|
-
const exporter = new ConsoleLogPrettyExporter();
|
|
644
|
-
const processor = new SimpleLogRecordProcessor(exporter);
|
|
645
|
-
return new LoggerProvider({
|
|
646
|
-
resource,
|
|
647
|
-
processors: [processor]
|
|
648
|
-
});
|
|
649
|
-
};
|
|
650
|
-
var getSpanProcessor = (otlpEndpoint) => {
|
|
651
|
-
const exporter = otlpEndpoint ? new OTLPTraceExporter({
|
|
652
|
-
url: `${otlpEndpoint}/v1/traces`
|
|
653
|
-
}) : new ConsoleSpanPrettyExporter();
|
|
654
|
-
const processor = otlpEndpoint ? new BatchSpanProcessor(exporter) : new TreeSpanProcessor(exporter);
|
|
655
|
-
return processor;
|
|
656
|
-
};
|
|
657
|
-
var getMetricReader = (otlpEndpoint) => {
|
|
658
|
-
const metricExporter = otlpEndpoint ? new OTLPMetricExporter({
|
|
659
|
-
url: `${otlpEndpoint}/v1/metrics`
|
|
660
|
-
}) : new ConsoleMetricPrettyExporter();
|
|
661
|
-
const metricReader = new PeriodicExportingMetricReader({
|
|
662
|
-
exporter: metricExporter
|
|
663
|
-
});
|
|
664
|
-
return metricReader;
|
|
665
|
-
};
|
|
666
|
-
|
|
667
|
-
// src/resource.ts
|
|
668
|
-
import { containerDetector } from "@opentelemetry/resource-detector-container";
|
|
669
|
-
import { gcpDetector } from "@opentelemetry/resource-detector-gcp";
|
|
670
|
-
import {
|
|
671
|
-
detectResources,
|
|
672
|
-
envDetector,
|
|
673
|
-
osDetector,
|
|
674
|
-
processDetector,
|
|
675
|
-
resourceFromAttributes,
|
|
676
|
-
serviceInstanceIdDetector
|
|
677
|
-
} from "@opentelemetry/resources";
|
|
678
|
-
|
|
679
|
-
// src/otel-context.ts
|
|
680
|
-
import {
|
|
681
|
-
ATTR_SERVICE_NAME as ATTR_SERVICE_NAME2,
|
|
682
|
-
ATTR_SERVICE_VERSION as ATTR_SERVICE_VERSION2
|
|
683
|
-
} from "@opentelemetry/semantic-conventions";
|
|
684
|
-
function detectTelemetryContext(componentNameOverride) {
|
|
685
|
-
const {
|
|
686
|
-
OTEL_SERVICE_NAME,
|
|
687
|
-
// e.g. "UserSystem"
|
|
688
|
-
OTEL_SERVICE_VERSION,
|
|
689
|
-
// e.g. "1.2.3"
|
|
690
|
-
K_SERVICE,
|
|
691
|
-
K_REVISION,
|
|
692
|
-
K_CONFIGURATION,
|
|
693
|
-
KUBERNETES_SERVICE_HOST,
|
|
694
|
-
POD_NAME,
|
|
695
|
-
POD_NAMESPACE,
|
|
696
|
-
GCP_PROJECT,
|
|
697
|
-
CLOUD_PROVIDER
|
|
698
|
-
} = process.env;
|
|
699
|
-
const systemName = OTEL_SERVICE_NAME || "unknown-service";
|
|
700
|
-
const systemVersion = OTEL_SERVICE_VERSION || "1.0.0";
|
|
701
|
-
const componentName = componentNameOverride || void 0;
|
|
702
|
-
const resourceAttributes = {
|
|
703
|
-
[ATTR_SERVICE_NAME2]: systemName,
|
|
704
|
-
[ATTR_SERVICE_VERSION2]: systemVersion,
|
|
705
|
-
"serviceContext.service": systemName,
|
|
706
|
-
"serviceContext.version": systemVersion,
|
|
707
|
-
...K_SERVICE && { "cloud.run.service": K_SERVICE },
|
|
708
|
-
...K_REVISION && { "cloud.run.revision": K_REVISION },
|
|
709
|
-
...K_CONFIGURATION && { "cloud.run.configuration": K_CONFIGURATION },
|
|
710
|
-
...POD_NAME && { "k8s.pod_name": POD_NAME },
|
|
711
|
-
...POD_NAMESPACE && { "k8s.namespace_name": POD_NAMESPACE },
|
|
712
|
-
...KUBERNETES_SERVICE_HOST && { "cloud.orchestrator": "kubernetes" },
|
|
713
|
-
...GCP_PROJECT && { "cloud.account.id": GCP_PROJECT },
|
|
714
|
-
...CLOUD_PROVIDER && { "cloud.provider": CLOUD_PROVIDER },
|
|
715
|
-
...componentName && { "component.name": componentName }
|
|
716
|
-
};
|
|
717
|
-
return {
|
|
718
|
-
systemName,
|
|
719
|
-
systemVersion,
|
|
720
|
-
componentName,
|
|
721
|
-
resourceAttributes
|
|
722
|
-
};
|
|
723
|
-
}
|
|
724
|
-
|
|
725
|
-
// src/resource.ts
|
|
726
|
-
var getResource = async () => {
|
|
727
|
-
const baseRes = await detectResources({
|
|
728
|
-
detectors: [
|
|
729
|
-
containerDetector,
|
|
730
|
-
envDetector,
|
|
731
|
-
gcpDetector,
|
|
732
|
-
osDetector,
|
|
733
|
-
processDetector,
|
|
734
|
-
serviceInstanceIdDetector
|
|
735
|
-
]
|
|
736
|
-
});
|
|
737
|
-
if (baseRes.waitForAsyncAttributes) {
|
|
738
|
-
await baseRes.waitForAsyncAttributes();
|
|
739
|
-
}
|
|
740
|
-
const { resourceAttributes } = detectTelemetryContext();
|
|
741
|
-
const customRes = resourceFromAttributes(resourceAttributes);
|
|
742
|
-
const resource = baseRes.merge(customRes);
|
|
743
|
-
if (resource.waitForAsyncAttributes) {
|
|
744
|
-
await resource.waitForAsyncAttributes();
|
|
745
|
-
}
|
|
746
|
-
return resource;
|
|
747
|
-
};
|
|
748
|
-
|
|
749
|
-
// src/otel.ts
|
|
750
|
-
diag.disable();
|
|
751
|
-
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.ERROR);
|
|
752
|
-
var initialization;
|
|
753
|
-
var _isInitialized = false;
|
|
754
|
-
async function initialize(...instrumentations2) {
|
|
755
|
-
if (!initialization) {
|
|
756
|
-
const resolvedInstrumentations = await Promise.all(instrumentations2);
|
|
757
|
-
initialization = _initialize(resolvedInstrumentations);
|
|
758
|
-
initialization.then(() => {
|
|
759
|
-
_isInitialized = true;
|
|
760
|
-
});
|
|
761
|
-
}
|
|
762
|
-
return initialization;
|
|
763
|
-
}
|
|
764
|
-
function isInitialized() {
|
|
765
|
-
return _isInitialized;
|
|
766
|
-
}
|
|
767
|
-
async function _initialize(instrumentations2) {
|
|
768
|
-
try {
|
|
769
|
-
const serviceName = process.env.OTEL_SERVICE_NAME ?? "unknown-service";
|
|
770
|
-
const otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
|
771
|
-
const resource = await getResource();
|
|
772
|
-
context.disable();
|
|
773
|
-
logs.disable();
|
|
774
|
-
trace.disable();
|
|
775
|
-
metrics.disable();
|
|
776
|
-
const logProvider = getLogProvider(resource, otlpEndpoint);
|
|
777
|
-
logs.setGlobalLoggerProvider(logProvider);
|
|
778
|
-
const spanProcessor = getSpanProcessor(otlpEndpoint);
|
|
779
|
-
const metricReader = getMetricReader(otlpEndpoint);
|
|
780
|
-
const sdk = new NodeSDK({
|
|
781
|
-
spanProcessor,
|
|
782
|
-
metricReader,
|
|
783
|
-
instrumentations: instrumentations2,
|
|
784
|
-
resource
|
|
785
|
-
});
|
|
786
|
-
await sdk.start();
|
|
787
|
-
console.log(`[otel] Telemetry initialized for "${serviceName}"`);
|
|
788
|
-
process.on("SIGTERM", async () => {
|
|
789
|
-
console.log("[otel] Shutting down...");
|
|
790
|
-
await Promise.all([sdk.shutdown(), logProvider.shutdown()]);
|
|
791
|
-
console.log("[otel] Shutdown complete.");
|
|
792
|
-
process.exit(0);
|
|
793
|
-
});
|
|
794
|
-
} catch (err) {
|
|
795
|
-
console.error("[otel] Startup error:", err);
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
// src/logger.ts
|
|
800
|
-
function getLogger(serviceOverride, extraAttrs = {}) {
|
|
801
|
-
const { systemName, systemVersion, resourceAttributes } = detectTelemetryContext(serviceOverride);
|
|
802
|
-
const defaultAttrs = {
|
|
803
|
-
...resourceAttributes,
|
|
804
|
-
...extraAttrs
|
|
805
|
-
};
|
|
806
|
-
function emit(severityText, body, attrs = {}) {
|
|
807
|
-
if (!isInitialized() && process.env.NODE_ENV !== "test") {
|
|
808
|
-
console.warn("OTEL must be initialized before using logger");
|
|
809
|
-
console.log(`[${severityText}] ${body}`);
|
|
810
|
-
return;
|
|
811
|
-
}
|
|
812
|
-
const logger = logs2.getLogger(systemName, systemVersion);
|
|
813
|
-
const span = trace2.getSpan(context2.active());
|
|
814
|
-
const spanContext = span?.spanContext();
|
|
815
|
-
logger.emit({
|
|
816
|
-
severityText,
|
|
817
|
-
severityNumber: LOG_SEVERITY_MAP[severityText],
|
|
818
|
-
body,
|
|
819
|
-
attributes: {
|
|
820
|
-
...defaultAttrs,
|
|
821
|
-
...spanContext && {
|
|
822
|
-
trace_id: spanContext.traceId,
|
|
823
|
-
span_id: spanContext.spanId
|
|
824
|
-
},
|
|
825
|
-
...attrs
|
|
826
|
-
}
|
|
827
|
-
});
|
|
828
|
-
}
|
|
829
|
-
return {
|
|
830
|
-
debug: (msg, attrs) => emit("DEBUG", msg, attrs),
|
|
831
|
-
info: (msg, attrs) => emit("INFO", msg, attrs),
|
|
832
|
-
notice: (msg, attrs) => emit("NOTICE", msg, attrs),
|
|
833
|
-
warn: (msg, attrs) => emit("WARNING", msg, attrs),
|
|
834
|
-
error: (msg, errOrAttrs, maybeAttrs = {}) => {
|
|
835
|
-
let body;
|
|
836
|
-
let attrs;
|
|
837
|
-
if (errOrAttrs instanceof Error) {
|
|
838
|
-
body = `${msg}: ${errOrAttrs.stack || errOrAttrs.message}`;
|
|
839
|
-
attrs = maybeAttrs;
|
|
840
|
-
} else {
|
|
841
|
-
body = msg instanceof Error ? msg.stack || msg.message : msg;
|
|
842
|
-
attrs = errOrAttrs || {};
|
|
843
|
-
}
|
|
844
|
-
emit("ERROR", body, attrs);
|
|
845
|
-
},
|
|
846
|
-
critical: (msg, attrs) => emit("CRITICAL", msg, attrs),
|
|
847
|
-
alert: (msg, attrs) => emit("ALERT", msg, attrs),
|
|
848
|
-
emergency: (msg, attrs) => emit("EMERGENCY", msg, attrs)
|
|
849
|
-
};
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
// src/metrics.ts
|
|
853
|
-
import { metrics as metrics2 } from "@opentelemetry/api";
|
|
854
|
-
function getMeter(componentNameOverride) {
|
|
855
|
-
if (!isInitialized() && process.env.NODE_ENV !== "test") {
|
|
856
|
-
console.warn("OTEL must be initialized before using getMeter()");
|
|
857
|
-
}
|
|
858
|
-
const { componentName, systemName, systemVersion } = detectTelemetryContext(
|
|
859
|
-
componentNameOverride
|
|
860
|
-
);
|
|
861
|
-
return metrics2.getMeter(componentName ?? systemName, systemVersion);
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
// src/tracer.ts
|
|
865
|
-
import {
|
|
866
|
-
context as context3,
|
|
867
|
-
SpanStatusCode as SpanStatusCode3,
|
|
868
|
-
trace as trace3
|
|
869
|
-
} from "@opentelemetry/api";
|
|
870
|
-
function getTracer(componentNameOverride) {
|
|
871
|
-
if (!isInitialized() && process.env.NODE_ENV !== "test") {
|
|
872
|
-
console.warn("OTEL must be initialized before calling getTracer()");
|
|
873
|
-
}
|
|
874
|
-
const { componentName, systemName, systemVersion } = detectTelemetryContext(
|
|
875
|
-
componentNameOverride
|
|
876
|
-
);
|
|
877
|
-
const tracer = trace3.getTracer(
|
|
878
|
-
componentName ?? systemName,
|
|
879
|
-
systemVersion
|
|
880
|
-
);
|
|
881
|
-
const withTrace = async (name, spanOptionsSpanOrFunc, spanOrFunc, func) => {
|
|
882
|
-
const { options, parent, fn } = extractArgs(
|
|
883
|
-
spanOptionsSpanOrFunc,
|
|
884
|
-
spanOrFunc,
|
|
885
|
-
func
|
|
886
|
-
);
|
|
887
|
-
const parentContext = parent ? trace3.setSpan(context3.active(), parent) : context3.active();
|
|
888
|
-
const span = tracer.startSpan(name, options, parentContext);
|
|
889
|
-
return await context3.with(trace3.setSpan(parentContext, span), async () => {
|
|
890
|
-
try {
|
|
891
|
-
const result = await fn(span);
|
|
892
|
-
span.setStatus({ code: SpanStatusCode3.OK });
|
|
893
|
-
return result;
|
|
894
|
-
} catch (err) {
|
|
895
|
-
const error = err;
|
|
896
|
-
span.setStatus({ code: SpanStatusCode3.ERROR, message: error.message });
|
|
897
|
-
span.recordException?.(error);
|
|
898
|
-
throw err;
|
|
899
|
-
} finally {
|
|
900
|
-
span.end();
|
|
901
|
-
}
|
|
902
|
-
});
|
|
903
|
-
};
|
|
904
|
-
const withTraceSync = (name, spanOptionsSpanOrFunc, spanOrFunc, func) => {
|
|
905
|
-
const { options, parent, fn } = extractArgs(
|
|
906
|
-
spanOptionsSpanOrFunc,
|
|
907
|
-
spanOrFunc,
|
|
908
|
-
func
|
|
909
|
-
);
|
|
910
|
-
const parentContext = parent ? trace3.setSpan(context3.active(), parent) : context3.active();
|
|
911
|
-
const span = tracer.startSpan(name, options, parentContext);
|
|
912
|
-
return context3.with(trace3.setSpan(parentContext, span), () => {
|
|
913
|
-
try {
|
|
914
|
-
const result = fn(span);
|
|
915
|
-
span.setStatus({ code: SpanStatusCode3.OK });
|
|
916
|
-
return result;
|
|
917
|
-
} catch (err) {
|
|
918
|
-
const error = err;
|
|
919
|
-
span.setStatus({ code: SpanStatusCode3.ERROR, message: error.message });
|
|
920
|
-
span.recordException?.(error);
|
|
921
|
-
throw err;
|
|
922
|
-
} finally {
|
|
923
|
-
span.end();
|
|
924
|
-
}
|
|
925
|
-
});
|
|
926
|
-
};
|
|
927
|
-
tracer.withTrace = withTrace;
|
|
928
|
-
tracer.withTraceSync = withTraceSync;
|
|
929
|
-
return tracer;
|
|
930
|
-
}
|
|
931
|
-
function extractArgs(spanOptionsSpanOrFunc, spanOrFunc, func) {
|
|
932
|
-
let options = {};
|
|
933
|
-
let parent;
|
|
934
|
-
let fn;
|
|
935
|
-
if (isFunction(spanOptionsSpanOrFunc)) {
|
|
936
|
-
fn = spanOptionsSpanOrFunc;
|
|
937
|
-
} else if (isFunction(spanOrFunc)) {
|
|
938
|
-
const spanOrSpanOptions = spanOptionsSpanOrFunc;
|
|
939
|
-
if (isSpanOptions(spanOrSpanOptions)) {
|
|
940
|
-
options = spanOrSpanOptions;
|
|
941
|
-
} else {
|
|
942
|
-
parent = spanOrSpanOptions;
|
|
943
|
-
}
|
|
944
|
-
fn = spanOrFunc;
|
|
945
|
-
} else {
|
|
946
|
-
options = spanOptionsSpanOrFunc;
|
|
947
|
-
parent = spanOrFunc;
|
|
948
|
-
fn = func;
|
|
949
|
-
}
|
|
950
|
-
return { options, parent, fn };
|
|
951
|
-
}
|
|
952
|
-
var isFunction = (value) => typeof value === "function";
|
|
953
|
-
var isSpan = (value) => value !== null && value !== void 0 && isFunction(value.spanContext) && isFunction(value.end);
|
|
954
|
-
var isSpanOptions = (value) => value !== null && value !== void 0 && (!!value.startTime || !!value.attributes || !!value.kind) && !isSpan(value);
|
|
955
|
-
export {
|
|
956
|
-
SpanStatusCode4 as SpanStatusCode,
|
|
957
|
-
context4 as context,
|
|
958
|
-
getLogger,
|
|
959
|
-
getMeter,
|
|
960
|
-
getTracer,
|
|
961
|
-
initialize,
|
|
962
|
-
instrumentations,
|
|
963
|
-
isInitialized
|
|
964
|
-
};
|
|
965
|
-
//# sourceMappingURL=index.js.map
|