@sebspark/otel 1.1.4 → 2.0.1

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