Migrate JavaScript OpenTelemetry APM
Overview
The OpenTelemetry JavaScript SDK supports both manual instrumentation via the API and automatic instrumentation via the auto-instrumentations-node package.
This page covers installing the SDK, setting up instrumentation, and configuring the OTLP exporter to send traces to Kloudfuse.
Install
Run these commands to install the core JavaScript packages:
npm install @opentelemetry/sdk-node \
@opentelemetry/api \
@opentelemetry/auto-instrumentations-node \
@opentelemetry/sdk-metrics \
@opentelemetry/sdk-trace-node \
@opentelemetry/exporter-trace-otlp-http
Set Up Instrumentation
Create a tracing.js file and require it before any other modules.
The SDK must be initialized before your application code loads, so it can patch imported libraries:
const { NodeSDK } = require('@opentelemetry/sdk-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const sdk = new NodeSDK({
traceExporter: new OTLPTraceExporter(),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
Start your application with tracing.js required first:
node --require ./tracing.js app.js
To create manual spans, use the global tracer:
const opentelemetry = require('@opentelemetry/api');
const tracer = opentelemetry.trace.getTracer('my-service');
const span = tracer.startSpan('my-operation');
// your work here
span.end();
For full setup details, follow the OpenTelemetry documentation on Manual Instrumentation Setup.
Send to Kloudfuse
Configure the OTLP exporter by setting the following environment variables before starting your application:
export OTEL_EXPORTER_OTLP_ENDPOINT="https://<kloudfuse-hostname>/ingester/otlp" (1)
export OTEL_EXPORTER_OTLP_HEADERS="Kf-Api-Key=<api-key>" (2)
export OTEL_SERVICE_NAME="my-service"
export OTEL_RESOURCE_ATTRIBUTES="deployment.environment=production"
| 1 | Replace <kloudfuse-hostname> with your Kloudfuse cluster hostname. |
| 2 | Replace <api-key> with your Kloudfuse API key. |
Instrumentation Libraries
OpenTelemetry JavaScript provides separate npm packages that automatically instrument popular libraries and frameworks. Review the OpenTelemetry Registry for JavaScript for available packages.
Troubleshooting
No Traces Appear
Confirm that tracing.js is required before any other modules.
If tracing.js is loaded after http, express, or other libraries, those modules will not be patched and no spans will be generated.
Using --require ./tracing.js on the command line is the safest approach as it guarantees load order.
Spans Missing for Specific Libraries
The auto-instrumentations-node package only instruments libraries for which a corresponding instrumentation package is installed.
If spans are missing for a specific library, check that the matching @opentelemetry/instrumentation-<lib> package is listed in your package.json or install it explicitly.