Node.js SDK
Node.js SDK
Section titled “Node.js SDK”Instrument your Node.js applications to send traces and logs to Kopai.
Installation
Section titled “Installation”npm install @opentelemetry/api @opentelemetry/sdk-node \ @opentelemetry/exporter-trace-otlp-http \ @opentelemetry/exporter-logs-otlp-http \ @opentelemetry/auto-instrumentations-nodeBasic Setup
Section titled “Basic Setup”Create a tracing.js file:
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({ url: "https://otlp.kopai.app/v1/traces", headers: { Authorization: `Bearer ${process.env.KOPAI_TOKEN}`, }, }), instrumentations: [getNodeAutoInstrumentations()],});
sdk.start();Running Your Application
Section titled “Running Your Application”export KOPAI_TOKEN="your-token-here"export OTEL_SERVICE_NAME="my-service"node --require ./tracing.js app.jsAuto-Instrumentation
Section titled “Auto-Instrumentation”The @opentelemetry/auto-instrumentations-node package provides automatic instrumentation for:
- HTTP/HTTPS
- Express, Fastify, Koa
- MongoDB, PostgreSQL, MySQL
- Redis, Memcached
- gRPC
- And more
Manual Instrumentation
Section titled “Manual Instrumentation”For custom spans:
const { trace } = require("@opentelemetry/api");
const tracer = trace.getTracer("my-service");
async function processOrder(orderId) { return tracer.startActiveSpan("processOrder", async (span) => { span.setAttribute("order.id", orderId); try { // Your logic here return result; } finally { span.end(); } });}