0.0.18 • Published 8 months ago

@autonomize/otel v0.0.18

Weekly downloads
-
License
-
Repository
-
Last release
8 months ago

Autonomize OTEL (@autonomize/otel)

A lightweight, easy-to-use OpenTelemetry SDK for Node.js and Nest.js applications. This SDK provides unified instrumentation for traces, metrics, and logs with automatic context propagation and built-in support for popular frameworks.

Features

Metrics Collection

  • Track custom metrics with counters, histograms, and up/down counters
  • Configurable metric export intervals
  • Pre-configured metric attributes
  • Direct access to OpenTelemetry metrics API

Distributed Tracing

  • Automatic trace context propagation
  • Built-in span creation and management
  • Custom attribute support
  • Support for error recording
  • Direct access to OpenTelemetry trace API

Structured Logging

  • Automatic trace correlation
  • Multiple severity levels (INFO, ERROR, WARN, DEBUG)
  • Custom attributes support
  • Error stack trace handling

Auto-Instrumentation

  • Initialization through env setup
  • No code changes required
  • HTTP client and server
  • Express.js framework
  • NestJS core components
  • Custom request hooks
  • Health check endpoint filtering

Installation

# Using npm
npm install @autonomize/otel

# Using yarn
yarn add @autonomize/otel

# Using pnpm
pnpm add @autonomize/otel

Quick Start

Auto-Instrumentation

The SDK supports automatic instrumentation of your Node.js application. To enable it:

  1. Set the NODE_OPTIONS environment variable:
NODE_OPTIONS="--require @autonomize/otel/register"
  1. Configure your environment variables (see Configuration section)

  2. Start your application normally:

node app.js # you start script here

Manual Initialization

If you prefer manual control over the SDK initialization:

import { OTEL } from '@autonomize/otel';

const otel = new OTEL({
  serviceName: 'my-service',
  environment: 'production',
  version: '1.0.0',
  otlpEndpoint: 'http://otlpendpoint:3000',
});

await otel.start();

// Your application code here

// On shutdown
await otel.shutdown();

Configuration

TelemetryConfig Options

OptionTypeRequiredDefaultDescription
serviceNamestringYes-Unique identifier for your service
environmentstringYes-Deployment environment (e.g., 'production')
versionstringNoundefinedService version
otlpEndpointstringNo'http://localhost:4318'OpenTelemetry collector endpoint
metricIntervalMsnumberNo5000Metric export interval in milliseconds

Updated Configuration Options

Environment VariableDescriptionDefault ValueType
OTEL_SERVICE_NAMEName of your service'unknown-service'string
OTEL_SERVICE_VERSIONVersion of your service'0.0.0'string
OTEL_ENVIRONMENTDeployment environment'development'string
OTEL_EXPORTER_OTLP_ENDPOINTOpenTelemetry Collector endpoint'http://localhost:4318'string
OTEL_HTTP_ENABLEDEnable HTTP instrumentationtrueboolean
OTEL_EXPRESS_ENABLEDEnable Express instrumentationtrueboolean
OTEL_NESTJS_ENABLEDEnable NestJS instrumentationfalseboolean
OTEL_LOG_LEVELLog level (ERROR, WARN, INFO, DEBUG)'INFO'string
OTEL_METRIC_EXPORT_INTERVALMetrics export interval in ms5000number

Example .env file

# Basic Service Configuration
OTEL_SERVICE_NAME=my-service
OTEL_SERVICE_VERSION=1.0.0
OTEL_ENVIRONMENT=development

# OpenTelemetry Collector Endpoint
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318

# Instrumentation Configuration
OTEL_HTTP_ENABLED=true
OTEL_EXPRESS_ENABLED=true
OTEL_NESTJS_ENABLED=true

# Logging Configuration
OTEL_LOG_LEVEL=INFO

# Metrics Configuration
OTEL_METRIC_EXPORT_INTERVAL=5000

Usage Examples

Metrics (otel.metrics)

Metric TypeDescriptionUsage Example
CounterOnly increasesotel.metrics.createCounter(...)
HistogramDistribution of valuesotel.metrics.createHistogram(...)
UpDownCounterCan increase/decreaseotel.metrics.createUpDownCounter(...)

import { OTEL } from '@autonomize/otel';

const otel = new OTEL();

// Create counter
const requestCounter = otel.metrics.createCounter({
  name: 'http.requests.total',
  description: 'Total number of HTTP requests',
  unit: 'requests',
});

// Record metrics
requestCounter.add(1, { 'http.method': 'GET' });

// Create a histogram (distribution of values)
const histogram = otel.metrics.createHistogram({
  name: 'metric_name',
  description: 'metric description',
  unit: 'unit',
});

// Create an up/down counter (can increase/decrease)
const upDownCounter = otel.metrics.createUpDownCounter({
  name: 'metric_name',
  description: 'metric description',
  unit: 'unit',
});

// Access OpenTelemetry metrics API
const metricsAPI = otel.metrics.getMetrics();

Tracing (otel.tracing)

import { OTEL } from '@autonomize/otel';

const otel = new OTEL();

// Access OpenTelemetry trace API and context
const trace = otel.tracing.getTrace();
const context = otel.tracing.getContext();
const activeSpan = otel.tracing.getActiveSpan();

// Create a traced operation
await otel.tracing.createSpan('my-operation', async () => {
  // Your code here
  await doSomething();
});

// Add attributes to current span
otel.tracing.addAttributes({
  'custom.attribute': 'value',
});

// Record errors
try {
  await riskyOperation();
} catch (error) {
  otel.tracing.recordError(error);
  throw error;
}

Logging (otel.logging)

import { OTEL } from '@autonomize/otel';

const otel = new OTEL();

// Log with different levels
otel.logging.info('Operation successful', { operation: 'data-sync' });
otel.logging.error('Operation failed', new Error('Sync failed'));
otel.logging.debug('Debug information', { details: 'some debug data' });

NestJS Integration

import OTEL from '@autonomize/otel';

async function bootstrap() {
  const otel = new OTEL({
    serviceName: 'nest-service',
    environment: process.env.NODE_ENV,
  });

  await otel.start();

  const app = await NestFactory.create(AppModule);
  await app.listen(3000);

  // Graceful shutdown
  process.on('SIGTERM', async () => {
    await otel.shutdown();
    await app.close();
  });
}

Playground

To test new features or debug locally:

  1. Clone the repository:

    git clone https://github.com/autonomize-ai/autonomize-sdk-js.git
    cd autonomize-sdk-js
  2. Set up the playground:

    cd playground
    cp .env.example .env   # Configure your environment variables
    pnpm install
  3. Run the OTel playground:

    pnpm dev:otel

This will start a development environment where you can test SDK features without publishing to npm.

Requirements

RequirementVersion
Node.js>= 14.x
OpenTelemetry CollectorLatest stable

Dependencies

PackageVersion
@opentelemetry/api^1.7.0
@opentelemetry/sdk-node^0.54.1
@opentelemetry/auto-instrumentations-node^0.52.0
@opentelemetry/instrumentation-nestjs-core^0.41.0

See package.json for the complete list of dependencies.

Additional Resources