sb_opentelemetry
v1.0.3
Published
A simple, batteries-included OpenTelemetry setup package for Node.js applications with automatic instrumentation, logging, and graceful shutdown handling.
Readme
OpenTelemetry Node.js Setup
A simple, batteries-included OpenTelemetry setup package for Node.js applications with automatic instrumentation, logging, and graceful shutdown handling.
Features
- Easy Setup: One-line initialization with sensible defaults
- Comprehensive Observability: Traces, metrics, and logs all configured
- Auto-instrumentation: Automatically instruments popular Node.js libraries
- Console Patching: Automatically forwards console logs to OpenTelemetry
- Graceful Shutdown: Handles process termination signals properly
- Configurable: Customizable export intervals and batch sizes
- Safe Logging: Handles circular references and large objects gracefully
Installation
npm install sb_opentelemetryQuick Start
const { setupOpenTelemetry } = require('sb_opentelemetry');
// Basic setup
setupOpenTelemetry('http://localhost:4318', 'my-service');
// Your application code here
console.log('Hello, OpenTelemetry!'); // This will be sent as a logAPI Reference
setupOpenTelemetry(url, serviceName, config?)
Initializes OpenTelemetry with the specified configuration.
Parameters
url(string, required): The OTLP endpoint URL (e.g., 'http://localhost:4318')serviceName(string, required): The name of your serviceconfig(object, optional): Configuration options
Configuration Options
const config = {
traces: {
maxQueueSize: 500, // Maximum queue size for spans
maxExportBatchSize: 100, // Maximum batch size for export
scheduledDelayMillis: 5000, // Delay between exports
exportTimeoutMillis: 30000 // Export timeout
},
metrics: {
exportIntervalMillis: 6000 // Metrics export interval
},
logs: {
maxQueueSize: 100, // Maximum queue size for logs
maxExportBatchSize: 20, // Maximum batch size for export
scheduledDelayMillis: 5000, // Delay between exports
exportTimeoutMillis: 30000 // Export timeout
}
};
setupOpenTelemetry('http://localhost:4318', 'my-service', config);Return Value
Returns an object with:
logger: OpenTelemetry logger instancesdk: OpenTelemetry SDK instance
Returns undefined if setup fails.
Usage Examples
Basic Setup
const { setupOpenTelemetry } = require('sb_opentelemetry');
// Initialize OpenTelemetry
const otel = setupOpenTelemetry('http://localhost:4318', 'user-service');
if (otel) {
console.log('OpenTelemetry initialized successfully');
} else {
console.error('Failed to initialize OpenTelemetry');
}
// Your Express app or other code
const express = require('express');
const app = express();
app.get('/', (req, res) => {
console.log('Handling root request'); // Automatically logged
res.json({ message: 'Hello World' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});With Custom Configuration
const { setupOpenTelemetry } = require('your-otel-package-name');
const config = {
traces: {
maxQueueSize: 1000,
scheduledDelayMillis: 3000
},
metrics: {
exportIntervalMillis: 10000
}
};
setupOpenTelemetry('https://api.honeycomb.io', 'production-service', config);Console Logging
The package automatically patches console.log, console.error, console.warn, and console.debug to forward logs to OpenTelemetry with appropriate severity levels:
console.log→ INFO levelconsole.error→ ERROR levelconsole.warn→ WARN levelconsole.debug→ DEBUG level
Large objects are automatically truncated and circular references are handled safely.
Auto-instrumentation
The package automatically instruments popular Node.js libraries including:
- HTTP/HTTPS
- Express
- Fastify
- MongoDB
- PostgreSQL
- MySQL
- Redis
- And many more
No additional configuration is required for basic instrumentation.
Graceful Shutdown
The package automatically handles process termination signals (SIGTERM, SIGINT) and ensures that all telemetry data is properly flushed before the process exits.
Error Handling
The setup function includes comprehensive error handling and will:
- Log setup errors to console
- Prevent duplicate initialization
- Continue running even if OpenTelemetry setup fails
Environment Variables
While not required, you can use environment variables for configuration:
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
OTEL_SERVICE_NAME=my-serviceTroubleshooting
Common Issues
"setupOpenTelemetry() was already called"
- The setup function can only be called once per process
- This warning indicates duplicate initialization attempts
No data appearing in collector
- Verify the OTLP endpoint URL is correct
- Check network connectivity to the collector
- Ensure the collector is running and accepting data
Performance impact
- Adjust batch sizes and export intervals if needed
- Monitor memory usage with large applications
Requirements
- Node.js 14 or higher
- An OpenTelemetry-compatible collector (Jaeger, Zipkin, Honeycomb, etc.)
Dependencies
This package includes all necessary OpenTelemetry dependencies:
- @opentelemetry/sdk-node
- @opentelemetry/auto-instrumentations-node
- @opentelemetry/exporter-trace-otlp-http
- @opentelemetry/exporter-metrics-otlp-http
- @opentelemetry/exporter-logs-otlp-http
