API Reference

Public API of the Sophonz Node.js SDK — init, shutdown, middleware, error handlers, trace attributes, logger transports, and the bundled official OpenTelemetry API.

Everything you need is exported from the @sophonz/node-sdk entry point, including the API tools from the latest stable official @opentelemetry/api. Import them from the SDK to use a single, version-pinned copy of the OpenTelemetry API.

Lifecycle

init(config?): void

Recommended entry point. Initializes the SDK with Sophonz defaults (console capture, exception capture, Sentry integration, programmatic imports) merged with your SDKConfig overrides. See Configuration.

initSDK(config): void

Lower-level initializer that applies only per-option defaults — no opinionated toggles. Use it for full control.

shutdown(): Promise<void>

Gracefully shut down the SDK and flush all pending telemetry. Called automatically on SIGTERM / SIGINT unless stopOnTerminationSignals is false.

import { init, shutdown } from '@sophonz/node-sdk';
 
init({ service: 'my-app' });
// ...
await shutdown();

Middleware

sophonzExpressMiddleware(options?): RequestHandler

Express request middleware that enriches the active span and mutable trace context with baggage, client IP, user-agent, and custom attributes. See Middleware.

sophonzKoaMiddleware(options?): Middleware

Koa equivalent of sophonzExpressMiddleware.

Both accept SophonzMiddlewareOptions: captureBaggage, captureClientIp, captureUserAgent, and attributes.

Error handling

setupExpressErrorHandler(app): void

Registers an Express error-handling middleware that records errors (status >= 500 by default). Call after your routes.

setupKoaErrorHandler(app): void

Wraps the Koa middleware chain in try/catch and records thrown errors.

recordException(error, hint?): Promise<void>

Manually record an exception. The optional hint accepts { tracer?, span?, attributes?, ... } plus standard event-hint fields.

import { recordException } from '@sophonz/node-sdk';
 
await recordException(err, { attributes: { 'job.name': 'nightly-sync' } });

Trace attributes

setTraceAttributes(attributes): void

Set attributes on the mutable async-local trace context so they propagate to spans created later in the same request. This is what the framework middleware uses internally.

import { setTraceAttributes } from '@sophonz/node-sdk';
 
setTraceAttributes({ 'enduser.id': userId });

Logger transports

Bridge your existing logger into Sophonz logs:

import { getWinstonTransport, getPinoTransport } from '@sophonz/node-sdk';
 
// Winston
logger.add(getWinstonTransport('info'));
 
// Pino
const transport = getPinoTransport('info');

getPinoMixinFunction is also exported for enriching Pino log records with trace context.

Debugging

enableDebugPayloadExporters(): Promise<void>

Attach console exporters to the initialized providers so every exported span and log record is printed to the terminal alongside the OTLP exporter. Call after init / initSDK.

import { init, enableDebugPayloadExporters } from '@sophonz/node-sdk';
 
init({ service: 'my-app' });
if (process.env.SOPHONZ_DEBUG_PAYLOAD === 'true') {
  void enableDebugPayloadExporters();
}

GCP

registerGCPCloudFunctionEventHandler(...)

Helper for instrumenting Google Cloud Function event handlers.

Official OpenTelemetry API

The SDK bundles the API tools from the latest stable official @opentelemetry/api and @opentelemetry/api-logs. Import them from the SDK:

import { trace, context, propagation, metrics, logs } from '@sophonz/node-sdk';
 
const span = trace.getActiveSpan();
span?.setAttribute('cart.size', items.length);

Available values: context, diag, metrics, propagation, trace, ProxyTracerProvider, SpanKind, SpanStatusCode, ValueType, createContextKey, isSpanContextValid, isValidSpanId, isValidTraceId, logs, SeverityNumber.

Available types: Attributes, AttributeValue, Baggage, BaggageEntry, Context, Counter, Histogram, Meter, Span, SpanContext, SpanOptions, TextMapPropagator, Tracer, TracerProvider, OtelApiLogger, LogRecord.