-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathotel.ts
More file actions
716 lines (661 loc) · 23.2 KB
/
otel.ts
File metadata and controls
716 lines (661 loc) · 23.2 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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
import { ExceptionInstrumentation } from '@hyperdx/instrumentation-exception';
import { SentryNodeInstrumentation } from '@hyperdx/instrumentation-sentry-node';
import { Attributes, diag, DiagLogLevel } from '@opentelemetry/api';
import {
getNodeAutoInstrumentations,
InstrumentationConfigMap,
} from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter as OTLPTraceExporterGRPC } from '@opentelemetry/exporter-trace-otlp-grpc';
import { OTLPTraceExporter as OTLPTraceExporterHTTP } from '@opentelemetry/exporter-trace-otlp-proto';
import {
InstrumentationBase,
InstrumentationModuleDefinition,
} from '@opentelemetry/instrumentation';
import { RuntimeNodeInstrumentation } from '@opentelemetry/instrumentation-runtime-node';
import { Resource, ResourceAttributes } from '@opentelemetry/resources';
import { MetricReader } from '@opentelemetry/sdk-metrics';
import { NodeSDK } from '@opentelemetry/sdk-node';
import cliSpinners from 'cli-spinners';
import fetch from 'node-fetch';
import ora from 'ora';
import path from 'path';
import * as semver from 'semver';
import { wrap } from 'shimmer';
import { version as PKG_VERSION } from '../package.json';
import {
DEFAULT_HDX_API_KEY,
DEFAULT_HDX_NODE_ADVANCED_NETWORK_CAPTURE,
DEFAULT_HDX_NODE_BETA_MODE,
DEFAULT_HDX_NODE_CONSOLE_CAPTURE,
DEFAULT_HDX_NODE_EXPERIMENTAL_EXCEPTION_CAPTURE,
DEFAULT_HDX_NODE_SENTRY_INTEGRATION_ENABLED,
DEFAULT_HDX_NODE_STOP_ON_TERMINATION_SIGNALS,
DEFAULT_HDX_STARTUP_LOGS,
DEFAULT_OTEL_EXPORTER_OTLP_TRACES_TIMEOUT,
DEFAULT_OTEL_LOG_LEVEL,
DEFAULT_OTEL_LOGS_EXPORTER,
DEFAULT_OTEL_LOGS_EXPORTER_URL,
DEFAULT_OTEL_METRICS_EXPORTER,
DEFAULT_OTEL_METRICS_EXPORTER_URL,
DEFAULT_OTEL_TRACES_EXPORTER,
DEFAULT_OTEL_TRACES_EXPORTER_URL,
DEFAULT_OTEL_TRACES_SAMPLER,
DEFAULT_OTEL_TRACES_SAMPLER_ARG,
DEFAULT_SERVICE_NAME,
} from './constants';
import HyperDXConsoleInstrumentation from './instrumentations/console';
import { getHyperDXHTTPInstrumentationConfig } from './instrumentations/http';
import { getHyperDXMetricReader } from './metrics';
import { MutableAsyncLocalStorageContextManager } from './MutableAsyncLocalStorageContextManager';
import { Logger as OtelLogger } from './otel-logger';
import HyperDXSpanProcessor from './spanProcessor';
import { parseOtlpHeaders } from './utils';
const UI_LOG_PREFIX = '[⚡HyperDX]';
const env = process.env;
const IS_LOCAL = env.NODE_ENV === 'development' || !env.NODE_ENV;
export type SDKConfig = {
additionalInstrumentations?: InstrumentationBase[];
additionalResourceAttributes?: ResourceAttributes;
advancedNetworkCapture?: boolean;
apiKey?: string;
betaMode?: boolean;
consoleCapture?: boolean;
detectResources?: boolean;
disableLogs?: boolean;
disableMetrics?: boolean;
disableStartupLogs?: boolean;
disableTracing?: boolean;
enableInternalProfiling?: boolean;
experimentalExceptionCapture?: boolean;
instrumentations?: InstrumentationConfigMap;
metricReader?: MetricReader;
programmaticImports?: boolean; // TEMP
sentryIntegrationEnabled?: boolean;
service?: string;
stopOnTerminationSignals?: boolean;
url?: string;
};
const setOtelEnvs = ({
apiKey,
disableLogs,
disableMetrics,
disableTracing,
service,
}: {
apiKey?: string;
disableLogs: boolean;
disableMetrics: boolean;
disableTracing: boolean;
service: string;
}) => {
// set default otel env vars
env.OTEL_NODE_RESOURCE_DETECTORS = env.OTEL_NODE_RESOURCE_DETECTORS ?? 'all';
env.OTEL_TRACES_SAMPLER = DEFAULT_OTEL_TRACES_SAMPLER;
env.OTEL_TRACES_SAMPLER_ARG = DEFAULT_OTEL_TRACES_SAMPLER_ARG;
env.OTEL_SERVICE_NAME = service;
if (disableLogs) {
env.OTEL_LOGS_EXPORTER = 'none';
}
if (disableTracing) {
env.OTEL_TRACES_EXPORTER = 'none';
}
if (disableMetrics) {
env.OTEL_METRICS_EXPORTER = 'none';
}
if (apiKey) {
if (env.OTEL_EXPORTER_OTLP_HEADERS) {
env.OTEL_EXPORTER_OTLP_HEADERS = `${env.OTEL_EXPORTER_OTLP_HEADERS},Authorization=${apiKey}`;
} else {
env.OTEL_EXPORTER_OTLP_HEADERS = `Authorization=${apiKey}`;
}
}
};
let sdk: NodeSDK;
let contextManager: MutableAsyncLocalStorageContextManager | undefined;
const getModuleId = (moduleName: string) => {
try {
const moduleId = require.resolve(moduleName);
return moduleId;
} catch (e) {
return null;
}
};
// https://github.com/open-telemetry/opentelemetry-js/blob/e49c4c7f42c6c444da3f802687cfa4f2d6983f46/experimental/packages/opentelemetry-instrumentation/src/platform/node/instrumentation.ts#L360
const isSupported = (
supportedVersions: string[],
version?: string,
includePrerelease?: boolean,
): boolean => {
if (typeof version === 'undefined') {
// If we don't have the version, accept the wildcard case only
return supportedVersions.includes('*');
}
return supportedVersions.some((supportedVersion) => {
return semver.satisfies(version, supportedVersion, { includePrerelease });
});
};
const hrtimeToMs = (hrtime: [number, number]) => {
return hrtime[0] * 1e3 + hrtime[1] / 1e6;
};
const healthCheckUrl = async (
ui: ora.Ora,
url: string,
requestConfigs: {
method: string;
headers?: Record<string, string>;
body?: string;
},
) => {
ui.text = `Checking health of ${url}...`;
try {
const res = await fetch(url, requestConfigs);
if (res.ok) {
ui.succeed(`Health check passed for ${url}`);
} else {
ui.fail(`Health check failed for ${url}`);
}
} catch (e) {
diag.error('Error checking health of url', e);
ui.fail(`Health check failed for ${url}`);
}
};
export const initSDK = (config: SDKConfig) => {
const defaultDisableStartupLogs =
config.disableStartupLogs ?? !DEFAULT_HDX_STARTUP_LOGS;
const ui = ora({
isSilent: defaultDisableStartupLogs,
prefixText: UI_LOG_PREFIX,
spinner: cliSpinners.dots,
text: 'Initializing OpenTelemetry SDK...',
}).start();
const defaultApiKey = config.apiKey ?? DEFAULT_HDX_API_KEY();
const defaultDetectResources = config.detectResources ?? true;
const defaultDisableLogs =
config.disableLogs ?? DEFAULT_OTEL_LOGS_EXPORTER === 'none';
const defaultDisableMetrics =
config.disableMetrics ?? DEFAULT_OTEL_METRICS_EXPORTER === 'none';
const defaultDisableTracing =
config.disableTracing ?? DEFAULT_OTEL_TRACES_EXPORTER === 'none';
const defaultEnableInternalProfiling =
config.enableInternalProfiling ?? false;
const defaultServiceName = config.service ?? DEFAULT_SERVICE_NAME();
// Override OTLP endpoint URLs if config.url is provided
const otlpEndpoint = config.url ?? env.OTEL_EXPORTER_OTLP_ENDPOINT;
const tracesUrl = otlpEndpoint ? `${otlpEndpoint}/v1/traces` : DEFAULT_OTEL_TRACES_EXPORTER_URL;
const logsUrl = otlpEndpoint ? `${otlpEndpoint}/v1/logs` : DEFAULT_OTEL_LOGS_EXPORTER_URL;
const metricsUrl = otlpEndpoint ? `${otlpEndpoint}/v1/metrics` : DEFAULT_OTEL_METRICS_EXPORTER_URL;
ui.succeed(`Service name is configured to be "${defaultServiceName}"`);
if (!env.OTEL_EXPORTER_OTLP_HEADERS && !defaultApiKey) {
ui.fail(
'apiKey or HYPERDX_API_KEY or OTEL_EXPORTER_OTLP_HEADERS is not set',
);
ui.stopAndPersist({
text: 'OpenTelemetry SDK initialization skipped',
symbol: '🚫',
});
return;
}
ui.text = 'Setting otel envs...';
setOtelEnvs({
apiKey: defaultApiKey,
disableLogs: defaultDisableLogs,
disableMetrics: defaultDisableMetrics,
disableTracing: defaultDisableTracing,
service: defaultServiceName,
});
ui.succeed('Set default otel envs');
// Parse OTLP headers from environment variable
const otlpHeaders = parseOtlpHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);
const healthCheckHeaders = {
'Content-Type': 'application/json',
...otlpHeaders,
};
const stopOnTerminationSignals =
config.stopOnTerminationSignals ??
DEFAULT_HDX_NODE_STOP_ON_TERMINATION_SIGNALS; // Stop by default
let defaultConsoleCapture =
config.consoleCapture ?? DEFAULT_HDX_NODE_CONSOLE_CAPTURE;
if (DEFAULT_OTEL_LOG_LEVEL === DiagLogLevel.DEBUG) {
// FIXME: better to disable console instrumentation if otel log is enabled
defaultConsoleCapture = false;
ui.warn(
`OTEL_LOG_LEVEL is set to 'debug', disabling console instrumentation`,
);
}
//--------------------------------------------------
// ------------------- LOGGER ----------------------
//--------------------------------------------------
ui.text = 'Initializing OpenTelemetry Logger...';
const _logger = new OtelLogger({
baseUrl: logsUrl,
detectResources: defaultDetectResources,
service: defaultServiceName,
});
ui.succeed('Initialized OpenTelemetry Logger');
//--------------------------------------------------
// Health check
Promise.all([
healthCheckUrl(ui, tracesUrl, {
method: 'POST',
headers: healthCheckHeaders,
body: JSON.stringify({}),
}),
healthCheckUrl(ui, _logger.getExporterUrl(), {
method: 'POST',
headers: healthCheckHeaders,
body: JSON.stringify({}),
}),
healthCheckUrl(ui, metricsUrl, {
method: 'POST',
headers: healthCheckHeaders,
body: JSON.stringify({}),
}),
]);
const defaultBetaMode = config.betaMode ?? DEFAULT_HDX_NODE_BETA_MODE();
const defaultAdvancedNetworkCapture =
config.advancedNetworkCapture ?? DEFAULT_HDX_NODE_ADVANCED_NETWORK_CAPTURE;
const defaultExceptionCapture =
config.experimentalExceptionCapture ??
DEFAULT_HDX_NODE_EXPERIMENTAL_EXCEPTION_CAPTURE;
const defaultSentryIntegrationEnabled =
config.sentryIntegrationEnabled ??
DEFAULT_HDX_NODE_SENTRY_INTEGRATION_ENABLED;
// Node 14.8.0+ has AsyncLocalStorage
// ref: https://github.com/open-telemetry/opentelemetry-js/blob/fd911fb3a4b5b05250750e0c0773aa0fc1e37706/packages/opentelemetry-sdk-trace-node/src/NodeTracerProvider.ts#L61C30-L61C67
contextManager = semver.gte(process.version, '14.8.0')
? new MutableAsyncLocalStorageContextManager()
: undefined;
ui.text = 'Initializing instrumentations packages...';
const allInstrumentations = [
...getNodeAutoInstrumentations({
'@opentelemetry/instrumentation-http': defaultAdvancedNetworkCapture
? getHyperDXHTTPInstrumentationConfig({
httpCaptureHeadersClientRequest:
env.OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST,
httpCaptureHeadersClientResponse:
env.OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE,
httpCaptureHeadersServerRequest:
env.OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST,
httpCaptureHeadersServerResponse:
env.OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE,
})
: { enabled: true },
// FIXME: issue detected with fs instrumentation (infinite loop)
'@opentelemetry/instrumentation-fs': {
enabled: false,
},
...config.instrumentations,
}),
new RuntimeNodeInstrumentation(),
...(defaultConsoleCapture
? [
new HyperDXConsoleInstrumentation({
betaMode: defaultBetaMode,
loggerOptions: {
baseUrl: _logger.getExporterUrl(),
service: defaultServiceName,
},
contextManager,
}),
]
: []),
...(defaultSentryIntegrationEnabled
? [new SentryNodeInstrumentation()]
: []),
...(defaultExceptionCapture
? [
new ExceptionInstrumentation({
_internalForceFlush: shutdown,
}),
]
: []),
...(config.additionalInstrumentations ?? []),
];
sdk = new NodeSDK({
resource: new Resource({
...config.additionalResourceAttributes,
// https://opentelemetry.io/docs/specs/semconv/resource/#telemetry-sdk-experimental
'telemetry.distro.name': 'hyperdx',
'telemetry.distro.version': PKG_VERSION,
}),
logRecordProcessor: defaultDisableLogs ? undefined : _logger.getProcessor(),
metricReader:
config.metricReader ??
(defaultDisableMetrics ? undefined : getHyperDXMetricReader(metricsUrl)),
spanProcessors: [
...(defaultDisableTracing
? []
: [
new HyperDXSpanProcessor({
exporter:
env.OTEL_EXPORTER_OTLP_PROTOCOL === 'grpc'
? new OTLPTraceExporterGRPC({
timeoutMillis: DEFAULT_OTEL_EXPORTER_OTLP_TRACES_TIMEOUT,
url: tracesUrl,
})
: new OTLPTraceExporterHTTP({
timeoutMillis: DEFAULT_OTEL_EXPORTER_OTLP_TRACES_TIMEOUT,
url: tracesUrl,
}),
enableHDXGlobalContext: defaultBetaMode,
contextManager,
}),
]),
],
instrumentations: config.programmaticImports ? [] : allInstrumentations,
contextManager: contextManager,
});
ui.succeed('Initialized instrumentations packages');
if (defaultEnableInternalProfiling) {
ui.text = 'Enabling internal profiling...';
for (const instrumentation of allInstrumentations) {
const _originalEnable = instrumentation.enable;
instrumentation.enable = function (...args: any[]) {
const start = process.hrtime();
// @ts-ignore
const result = _originalEnable.apply(this, args);
const end = process.hrtime(start);
ui.succeed(
`Enabled instrumentation ${
instrumentation.constructor.name
} in ${hrtimeToMs(end)} ms`,
);
return result;
};
const modules = (instrumentation as any)
._modules as InstrumentationModuleDefinition[];
for (const module of modules) {
if (typeof module.patch === 'function') {
// benchmark when patch gets called
wrap(module, 'patch', (original) => {
return (...args: any[]) => {
const start = process.hrtime();
// @ts-ignore
const result = original.apply(this, args);
const end = process.hrtime(start);
ui.succeed(
`Instrumented ${module.name}${
module.moduleVersion ? ` [v${module.moduleVersion}] ` : ' '
}in ${hrtimeToMs(end)} ms`,
);
return result;
};
});
}
for (const file of module.files) {
if (typeof file.patch === 'function') {
wrap(file, 'patch', (original) => {
return (...args: any[]) => {
const start = process.hrtime();
// @ts-ignore
const result = original.apply(this, args);
const end = process.hrtime(start);
ui.succeed(
`Instrumented ${module.name}${
module.moduleVersion ? ` [v${module.moduleVersion}] ` : ' '
}file ${file.name} in ${hrtimeToMs(end)} ms`,
);
return result;
};
});
}
}
}
}
}
ui.text = 'Starting OpenTelemetry Node SDK...';
sdk.start();
ui.succeed('Started OpenTelemetry Node SDK');
if (config.programmaticImports) {
ui.text = 'Repatching instrumentation packages...';
for (const instrumentation of allInstrumentations) {
const modules = (instrumentation as any)
._modules as InstrumentationModuleDefinition[];
if (Array.isArray(modules)) {
// disable first before re-patching
instrumentation.disable();
for (const module of modules) {
// re-require moduleExports
if (getModuleId(module.name)) {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const _m = require(module.name);
module.moduleExports = _m;
} catch (e) {
diag.error('Error re-requiring moduleExports for nodejs module', {
module: module.name,
version: module.moduleVersion,
error: e,
});
}
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const _pkg = require(path.join(module.name, 'package.json'));
module.moduleVersion = _pkg.version;
} catch (e) {
diag.error('Error re-requiring package.json for nodejs module', {
module: module.name,
version: module.moduleVersion,
error: e,
});
}
// https://github.com/open-telemetry/opentelemetry-js/blob/e49c4c7f42c6c444da3f802687cfa4f2d6983f46/experimental/packages/opentelemetry-instrumentation/src/platform/node/instrumentation.ts#L265
if (
isSupported(
module.supportedVersions,
module.moduleVersion,
module.includePrerelease,
) &&
typeof module.patch === 'function' &&
module.moduleExports
) {
diag.debug(
'Applying instrumentation patch for nodejs module on instrumentation enabled',
{
module: module.name,
version: module.moduleVersion,
},
);
try {
module.patch(module.moduleExports, module.moduleVersion);
} catch (e) {
diag.error(
'Error applying instrumentation patch for nodejs module',
e,
);
}
}
const files = module.files ?? [];
const supportedFileInstrumentations = files.filter((f) =>
isSupported(
f.supportedVersions,
module.moduleVersion,
module.includePrerelease,
),
);
for (const sfi of supportedFileInstrumentations) {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const _m = require(sfi.name);
sfi.moduleExports = _m;
} catch (e) {
diag.error(
'Error re-requiring moduleExports for nodejs module file',
e,
);
continue;
}
diag.debug(
'Applying instrumentation patch for nodejs module file on require hook',
{
module: module.name,
version: module.moduleVersion,
fileName: sfi.name,
},
);
try {
// patch signature is not typed, so we cast it assuming it's correct
sfi.patch(sfi.moduleExports, module.moduleVersion);
} catch (e) {
diag.error(
'Error applying instrumentation patch for nodejs module file',
e,
);
}
}
}
}
}
}
ui.succeed('Repatched instrumentation packages');
}
function handleTerminationSignal(signal: string) {
diag.debug(`${signal} received, shutting down...`);
_shutdown().finally(() => process.exit());
}
// Graceful shutdown
if (stopOnTerminationSignals) {
process.on('SIGTERM', () => {
handleTerminationSignal('SIGTERM');
});
process.on('SIGINT', () => {
handleTerminationSignal('SIGINT');
});
}
// Print out the configuration
if (defaultAdvancedNetworkCapture) {
ui.succeed(`Enabled Advanced Network Capture`);
}
if (defaultBetaMode) {
ui.succeed(`Enabled Beta Mode`);
}
if (defaultConsoleCapture) {
ui.succeed(`Enabled Console Capture`);
}
if (defaultDetectResources) {
ui.succeed(`Enabled Resource Detection`);
}
if (defaultExceptionCapture) {
ui.succeed(`Enabled Exception Capture`);
}
if (DEFAULT_OTEL_LOG_LEVEL) {
ui.succeed(`Enable SDK Logger with Level "${DEFAULT_OTEL_LOG_LEVEL}"`);
}
if (config.programmaticImports) {
ui.succeed(`Enabled Programmatic Imports`);
}
if (env.OTEL_PROPAGATORS) {
ui.succeed(`Using Propagators: "${env.OTEL_PROPAGATORS}"`);
}
if (env.OTEL_RESOURCE_ATTRIBUTES) {
ui.succeed(`Resource Attributes: "${env.OTEL_RESOURCE_ATTRIBUTES}"`);
}
if (env.OTEL_NODE_RESOURCE_DETECTORS) {
ui.succeed(`Resource Detectors: "${env.OTEL_NODE_RESOURCE_DETECTORS}"`);
}
if (DEFAULT_OTEL_TRACES_SAMPLER) {
ui.succeed(`Traces Sampler: "${DEFAULT_OTEL_TRACES_SAMPLER}"`);
}
if (defaultSentryIntegrationEnabled) {
ui.succeed(`Enabled Sentry Integration`);
}
if (stopOnTerminationSignals) {
ui.succeed('Enabled stopOnTerminationSignals');
} else {
ui.warn(
'Disabled stopOnTerminationSignals (user is responsible for graceful shutdown on termination signals)',
);
}
if (defaultDisableLogs) {
ui.warn('Logs are disabled');
} else {
ui.succeed(`Sending logs to "${logsUrl}"`);
}
if (defaultDisableMetrics) {
ui.warn('Metrics are disabled');
} else {
ui.succeed(`Sending metrics to "${metricsUrl}"`);
}
if (defaultDisableTracing) {
ui.warn('Tracing is disabled');
} else {
ui.succeed(`Sending traces to "${tracesUrl}"`);
}
ui.stopAndPersist({
text: `OpenTelemetry SDK initialized successfully`,
symbol: '🦄',
});
if (!defaultDisableStartupLogs) {
setTimeout(() => {
const _targetUrl = `https://www.hyperdx.io/services?service=${encodeURIComponent(
defaultServiceName,
)}`;
ui.info(`
View your app dashboard here:
${_targetUrl}
To disable these startup logs, set HDX_STARTUP_LOGS=false
`);
// Todo: not sure if this is a good idea...
// if (IS_LOCAL) {
// const _ui = ora({
// color: 'green',
// isSilent: !DEFAULT_HDX_STARTUP_LOGS,
// prefixText: UI_LOG_PREFIX,
// spinner: cliSpinners.arc,
// text: `Opening the dashboard...`,
// }).start();
// open(_targetUrl)
// .then(() => {
// _ui.succeed(`Opened dashboard in browser`);
// })
// .catch((e) => {
// _ui.fail(`Error opening browser: ${e}`);
// });
// }
}, 1000);
}
};
export const init = (config?: Omit<SDKConfig, 'programmaticImports'>) =>
initSDK({
consoleCapture: true,
experimentalExceptionCapture: true,
programmaticImports: true,
sentryIntegrationEnabled: true,
...config,
});
const _shutdown = () => {
const ui = ora({
spinner: cliSpinners.dots,
text: 'Shutting down OpenTelemetry SDK...',
}).start();
return (
sdk?.shutdown()?.then(
() => {
ui.succeed('OpenTelemetry SDK shut down successfully');
},
(err) => {
ui.fail(`Error shutting down OpenTeLoader SDK: ${err}`);
},
) ?? Promise.resolve() // in case SDK isn't init'd yet
);
};
export const shutdown = () => {
diag.debug('shutdown() called');
return _shutdown();
};
export const setTraceAttributes = (attributes: Attributes) => {
if (
contextManager &&
typeof contextManager.getMutableContext === 'function'
) {
const mutableContext = contextManager.getMutableContext();
if (mutableContext != null) {
if (mutableContext.traceAttributes == null) {
mutableContext.traceAttributes = new Map();
}
for (const [k, v] of Object.entries(attributes)) {
mutableContext.traceAttributes.set(k, v);
}
}
}
};