0.0.18 • Published 8 months ago
@autonomize/otel v0.0.18
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:
- Set the NODE_OPTIONS environment variable:
NODE_OPTIONS="--require @autonomize/otel/register"
Configure your environment variables (see Configuration section)
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
Option | Type | Required | Default | Description |
---|---|---|---|---|
serviceName | string | Yes | - | Unique identifier for your service |
environment | string | Yes | - | Deployment environment (e.g., 'production') |
version | string | No | undefined | Service version |
otlpEndpoint | string | No | 'http://localhost:4318' | OpenTelemetry collector endpoint |
metricIntervalMs | number | No | 5000 | Metric export interval in milliseconds |
Updated Configuration Options
Environment Variable | Description | Default Value | Type |
---|---|---|---|
OTEL_SERVICE_NAME | Name of your service | 'unknown-service' | string |
OTEL_SERVICE_VERSION | Version of your service | '0.0.0' | string |
OTEL_ENVIRONMENT | Deployment environment | 'development' | string |
OTEL_EXPORTER_OTLP_ENDPOINT | OpenTelemetry Collector endpoint | 'http://localhost:4318' | string |
OTEL_HTTP_ENABLED | Enable HTTP instrumentation | true | boolean |
OTEL_EXPRESS_ENABLED | Enable Express instrumentation | true | boolean |
OTEL_NESTJS_ENABLED | Enable NestJS instrumentation | false | boolean |
OTEL_LOG_LEVEL | Log level (ERROR, WARN, INFO, DEBUG) | 'INFO' | string |
OTEL_METRIC_EXPORT_INTERVAL | Metrics export interval in ms | 5000 | number |
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 Type | Description | Usage Example |
---|---|---|
Counter | Only increases | otel.metrics.createCounter(...) |
Histogram | Distribution of values | otel.metrics.createHistogram(...) |
UpDownCounter | Can increase/decrease | otel.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:
Clone the repository:
git clone https://github.com/autonomize-ai/autonomize-sdk-js.git cd autonomize-sdk-js
Set up the playground:
cd playground cp .env.example .env # Configure your environment variables pnpm install
Run the OTel playground:
pnpm dev:otel
This will start a development environment where you can test SDK features without publishing to npm.
Requirements
Requirement | Version |
---|---|
Node.js | >= 14.x |
OpenTelemetry Collector | Latest stable |
Dependencies
Package | Version |
---|---|
@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.