@voiceowl/otel-node-lib
v1.0.4
Published
Reusable OpenTelemetry library for Node.js microservices with Datadog integration
Maintainers
Readme
Voiceowl OpenTelemetry Library for Node.js
The @voiceowl/otel-node-lib package provides a reusable OpenTelemetry library for Node.js microservices, designed for seamless integration with observability platforms like Datadog. It simplifies the process of instrumenting your application for distributed tracing, metrics, and logging.
Features
- Zero-config setup: Get started quickly with a single initialization function.
- Automatic instrumentation: Automatically instruments popular Node.js libraries (e.g., Express, HTTP, DNS).
- Distributed tracing: Trace requests across multiple services to identify performance bottlenecks.
- Custom metrics: Capture application-specific metrics to monitor key performance indicators (KPIs).
- Structured logging: Enrich your logs with trace and span IDs for easy correlation.
- Express middleware: Provides middleware for request tracing, error handling, and request ID generation.
Installation
Install the package using npm:
npm install @voiceowl/otel-node-libQuick Start
The quickSetup function provides a simple way to initialize tracing, metrics, and logging with minimal configuration.
// src/index.ts
import { quickSetup } from '@voiceowl/otel-node-lib';
const { sdk, logger, metrics } = quickSetup({
serviceName: 'my-awesome-service',
otelCollectorUrl: 'http://localhost:4318', // OTLP/HTTP endpoint
});
// Your application logic here...
// Example of logging with trace context
logger.info('User logged in successfully', { userId: '123' });
// Example of a custom metric
const requestCounter = metrics.getCounter('http.requests.total');
requestCounter.add(1, { route: '/login' });
// Gracefully shut down the SDK on exit
process.on('SIGTERM', () => {
sdk.shutdown()
.then(() => console.log('Tracing terminated'))
.catch((error) => console.error('Error terminating tracing', error))
.finally(() => process.exit(0));
});Usage
Tracing
The initializeTracing function initializes the OpenTelemetry SDK for distributed tracing.
import { initializeTracing, shutdownTracing } from '@voiceowl/otel-node-lib';
const sdk = initializeTracing({
serviceName: 'my-service',
otelCollectorUrl: 'http://localhost:4318',
});
// Gracefully shut down the SDK on exit
process.on('SIGTERM', () => {
shutdownTracing()
.then(() => console.log('Tracing terminated'))
.catch((error) => console.error('Error terminating tracing', error))
.finally(() => process.exit(0));
});Metrics
The metricsProvider object provides access to the Meter API for creating and recording custom metrics.
import { metricsProvider } from '@voiceowl/otel-node-lib';
const meter = metricsProvider.getMeter('my-app');
const requestCounter = meter.createCounter('http.requests.total');
requestCounter.add(1, { route: '/users' });
const activeUsersGauge = meter.createObservableGauge('active.users');
activeUsersGauge.addCallback((result) => {
// Fetch the number of active users from your application
const activeUsers = getActiveUsers();
result.observe(activeUsers);
});Logging
The Logger class provides a simple interface for structured logging with trace context injection.
import { Logger, withTracing } from '@voiceowl/otel-node-lib';
const logger = new Logger('my-service');
// Logs with trace and span IDs
logger.info('User created successfully', { userId: '456' });
logger.error('Failed to process payment', { error: 'Insufficient funds' });
// Manually wrap a function with a new span
async function processOrder() {
return withTracing('processOrder', async (span) => {
// Your business logic here
span.setAttribute('orderId', '789');
logger.info('Processing order...');
});
}Middleware (for Express.js)
The library includes middleware for Express.js applications to simplify request tracing and error handling.
import express from 'express';
import { tracingMiddleware, errorTracingMiddleware, requestIdMiddleware } from '@voiceowl/otel-node-lib';
const app = express();
// Add request ID to all incoming requests
app.use(requestIdMiddleware());
// Enable tracing for all routes
app.use(tracingMiddleware({ serviceName: 'my-express-app' }));
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Add the error tracing middleware after all your routes
app.use(errorTracingMiddleware());
app.listen(3000, () => {
console.log('Server is running on port 3000');
});Configuration
The initializeTracing and quickSetup functions accept a configuration object with the following options:
| Option | Type | Description | Default |
| ------------------ | -------- | ------------------------------------------------------------------------------------------------------- | ------------------------------ |
| serviceName | string | Required. The name of your service or application. | - |
| otelCollectorUrl | string | The URL of your OpenTelemetry Collector (OTLP/HTTP or OTLP/gRPC). | http://localhost:4318 |
| logLevel | LogLevel | The minimum log level to capture. | LogLevel.INFO |
| instrumentations | any[] | An array of additional OpenTelemetry instrumentations to register. | [getNodeAutoInstrumentations()] |
Contributing
Contributions are welcome! Please open an issue or submit a pull request on our GitHub repository.
License
This project is licensed under the MIT License. See the LICENSE file for details.
