@sophonz/node-sdk
v0.2.0
Published
Readme
@sophonz/node-sdk
Complete OpenTelemetry SDK for Node.js with automatic instrumentation, exception handling, and console capture.
Part of the Sophonz OpenTelemetry suite.
Install
bun add @sophonz/node-sdk
# or
pnpm add @sophonz/node-sdk
# or
npm install @sophonz/node-sdkUsage
Programmatic Initialization
import { init, shutdown } from '@sophonz/node-sdk';
await init({
service: 'my-app',
apiKey: process.env.SOPHONZ_API_KEY,
consoleCapture: true,
experimentalExceptionCapture: true,
});
// Your application code here
console.log('Application running');
// Graceful shutdown
await shutdown();Framework request enrichers
Spans for Express, Koa, Fastify, and NestJS are created automatically by the
bundled auto-instrumentation. On top of that, the SDK ships per-framework
request enrichers that copy baggage entries onto the active span, capture the
client IP and user-agent, and forward them to the mutable trace context — so
applications never need to import @opentelemetry/api directly.
// Express
import express from 'express';
import { sophonzExpressMiddleware } from '@sophonz/node-sdk';
const app = express();
app.use(sophonzExpressMiddleware());// Koa
import Koa from 'koa';
import { sophonzKoaMiddleware } from '@sophonz/node-sdk';
const app = new Koa();
app.use(sophonzKoaMiddleware());// Fastify
import Fastify from 'fastify';
import { sophonzFastifyPlugin } from '@sophonz/node-sdk';
const app = Fastify();
await app.register(sophonzFastifyPlugin());// NestJS (works on both the Express and Fastify adapters)
import { NestFactory } from '@nestjs/core';
import { SophonzNestInterceptor } from '@sophonz/node-sdk';
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new SophonzNestInterceptor());All four accept the same options:
captureBaggage?: boolean- Copy baggage entries (prefixedbaggage.). Defaulttrue.captureClientIp?: boolean- Capturehttp.client.ip. Defaulttrue.captureUserAgent?: boolean- Capturehttp.user_agent. Defaulttrue.attributes?: Attributes | ((req) => Attributes)- Extra static or per-request attributes.
Ordering note: the SDK must be initialized (
init()) before the framework modules are loaded. The simplest pattern is to callinit()at the top of your entrypoint and load the app via dynamicimport()afterwards (see thesophonz-express-server/sophonz-fastify-server/sophonz-nestjs-serverexample apps).
Re-exported OpenTelemetry API
The OTel API surface is re-exported so you don't have to add
@opentelemetry/api / @opentelemetry/api-logs as direct dependencies:
import { trace, context, propagation, metrics, logs } from '@sophonz/node-sdk';
const span = trace.getActiveSpan();Debugging payloads
import { init, enableDebugPayloadExporters } from '@sophonz/node-sdk';
init({ service: 'my-app' });
if (process.env.SOPHONZ_DEBUG_PAYLOAD === 'true') {
// Dump every exported span/log to the terminal alongside the OTLP exporter.
void enableDebugPayloadExporters();
}Command-line Instrumentation
Wrap your Node.js application with the preload binary:
node -r @sophonz/node-sdk/build/bin/opentelemetry-instrument.js app.jsOr use the provided CLI:
opentelemetry-instrument app.jsAPI
init(config?: Partial<SDKConfig>): Promise<void>
Initialize the SDK with automatic instrumentation enabled.
initSDK(config: SDKConfig): void
Initialize the SDK with explicit configuration control.
shutdown(): Promise<void>
Gracefully shut down the SDK and flush all telemetry.
setTraceAttributes(attributes: Attributes): void
Set global trace attributes on the mutable context.
sophonzExpressMiddleware(options?): RequestHandler
Express request middleware that enriches the active span and mutable trace context with baggage, client IP, and user-agent.
sophonzKoaMiddleware(options?): Middleware
Koa equivalent of sophonzExpressMiddleware.
sophonzFastifyPlugin(options?): FastifyPluginCallback
Fastify plugin (registers an onRequest hook) that performs the same enrichment. Register with app.register(sophonzFastifyPlugin()).
SophonzNestInterceptor / sophonzNestInterceptor(options?)
NestJS NestInterceptor that performs the same enrichment. Register with app.useGlobalInterceptors(new SophonzNestInterceptor()). Works on both the Express and Fastify platform adapters.
enableDebugPayloadExporters(): Promise<void>
Attach console exporters to the initialized providers to print every span and log record. Call after init/initSDK.
SDKConfig Options
service?: string- Service name (default from env or auto-detected)apiKey?: string- API key for exporter authenticationconsoleCapture?: boolean- Instrument console API (default true)experimentalExceptionCapture?: boolean- Capture uncaught exceptions (default true)sentryIntegrationEnabled?: boolean- Enable Sentry integration (default true)advancedNetworkCapture?: boolean- Capture HTTP headers and bodiesdisableTracing?: boolean- Disable trace exportdisableLogs?: boolean- Disable log exportdisableMetrics?: boolean- Disable metric exportdisableStartupLogs?: boolean- Suppress initialization messagesstopOnTerminationSignals?: boolean- Graceful shutdown on SIGTERM/SIGINT (default true)detectResources?: boolean- Auto-detect resource attributes (default true)enableInternalProfiling?: boolean- Profile instrumentation startup timeadditionalInstrumentations?: InstrumentationBase[]- Custom instrumentationsinstrumentations?: InstrumentationConfigMap- Override auto-instrumentation configmetricReader?: MetricReader- Custom metric reader
Included Instrumentations
- HTTP/HTTPS
- Console API
- Node.js exceptions
- Sentry integration
- Runtime metrics
- Express / Koa / Fastify / NestJS (auto-instrumentation + request enrichers)
- Express/Koa error handlers
Peer dependencies
@opentelemetry/api@opentelemetry/sdk-node@opentelemetry/auto-instrumentations-node
Environment Variables
SOPHONZ_API_KEY- API key for exporterOTEL_SERVICE_NAME- Service nameOTEL_LOG_LEVEL- Diagnostics log levelSOPHONZ_STARTUP_LOGS- Show/hide initialization messages- Additional OTEL_* variables for OpenTelemetry configuration
License
See LICENSE in this package.
Part of sophonz-js.
