Skip to content
SaisinarePublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

πŸ” Observer - OpenTelemetry Observability Module

A production-ready, reusable observability module for Node.js APIs with OpenTelemetry, Prometheus metrics, and distributed tracing.

OpenTelemetry Prometheus Jaeger

✨ Features

  • βœ… Automatic HTTP Metrics - Request count, duration, active requests
  • βœ… Distributed Tracing - Full request traces with Jaeger
  • βœ… Zero Configuration - Works out of the box with sensible defaults
  • βœ… Completely Reusable - Drop into any Node.js API project
  • βœ… Framework Agnostic - Works with Express, Fastify, Koa, Native HTTP
  • βœ… Production Ready - Battle-tested patterns and best practices
  • βœ… Extensible - Easy to add custom business metrics

πŸš€ Quick Start

1. Install Dependencies

npm install express \
  @opentelemetry/api \
  @opentelemetry/sdk-node \
  @opentelemetry/sdk-metrics \
  @opentelemetry/exporter-prometheus \
  @opentelemetry/exporter-trace-otlp-http \
  @opentelemetry/auto-instrumentations-node \
  @opentelemetry/resources \
  @opentelemetry/semantic-conventions

2. Copy the Observability Module

Copy the obervability/ folder to your project:

your-project/
β”œβ”€β”€ obervability/
β”‚   β”œβ”€β”€ metrics.js
β”‚   β”œβ”€β”€ tracing.js
β”‚   └── README.md
└── server.js

3. Integrate (3 Lines of Code!)

const express = require('express');
const { initTracing } = require('./obervability/tracing');
const { initMetrics } = require('./obervability/metrics');

// Initialize observability
initTracing();
const { middleware } = initMetrics({
  serviceName: 'your-api',
  port: 9464
});

// Create your app
const app = express();
app.use(middleware);

// Your routes
app.get('/api/users', (req, res) => {
  res.json({ users: [] });
});

app.listen(3000);

That's it! You now have full observability! πŸŽ‰

πŸ“Š What You Get

Automatic Metrics

  • http_requests_total - Total HTTP requests by method, route, status
  • http_request_duration_ms - Request duration histogram
  • http_active_requests - Currently active requests gauge

Distributed Tracing

  • Automatic span creation for all HTTP requests
  • Context propagation across services
  • Integration with Jaeger for visualization

🎯 Use Cases

Basic Express API

const { initTracing } = require('./obervability/tracing');
const { initMetrics } = require('./obervability/metrics');

initTracing();
const { middleware } = initMetrics();

app.use(middleware);

Custom Business Metrics

const { initMetrics, getMeter } = require('./obervability/metrics');

const { middleware } = initMetrics();
app.use(middleware);

// Create custom metrics
const meter = getMeter();
const ordersProcessed = meter.createCounter('orders_processed_total');

app.post('/orders', (req, res) => {
  ordersProcessed.add(1, { status: 'success' });
  res.json({ orderId: '12345' });
});

Multiple Microservices

// Service A
initMetrics({ serviceName: 'user-service', port: 9464 });

// Service B
initMetrics({ serviceName: 'order-service', port: 9465 });

// Service C
initMetrics({ serviceName: 'payment-service', port: 9466 });

🐳 Docker Setup

Docker Compose

version: '3.8'

services:
  api:
    build: .
    ports:
      - "3000:3000"
      - "9464:9464"
    environment:
      SERVICE_NAME: my-api

  prometheus:
    image: prom/prometheus
    ports:
      - "9090:9090"
    volumes:
      - ./docker/prometheus.yml:/etc/prometheus/prometheus.yml

  jaeger:
    image: jaegertracing/all-in-one
    ports:
      - "16686:16686"
      - "4318:4318"

  grafana:
    image: grafana/grafana
    ports:
      - "3001:3000"

Prometheus Configuration

# docker/prometheus.yml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'api'
    static_configs:
      - targets: ['api:9464']

πŸ“ˆ Access Your Observability Stack

πŸ“š Documentation

πŸ”§ API Reference

initMetrics(config)

Initialize metrics infrastructure and create HTTP instruments.

const { middleware, meter, instruments } = initMetrics({
  port: 9464,              // Prometheus exporter port
  endpoint: '/metrics',     // Metrics endpoint path
  serviceName: 'my-api'    // Service name for metrics
});

getMeter()

Get meter instance for creating custom metrics.

const meter = getMeter();
const customCounter = meter.createCounter('my_custom_metric');
customCounter.add(1, { label: 'value' });

getHttpInstruments()

Get pre-created HTTP metric instruments.

const { httpRequestCounter, httpRequestDuration, activeRequests } = getHttpInstruments();

πŸŽ“ Best Practices

βœ… DO

  • Initialize metrics before creating Express app
  • Apply middleware before route handlers
  • Use meaningful service names
  • Keep label cardinality low
  • Create custom metrics for business logic

❌ DON'T

  • Don't create metrics inside route handlers
  • Don't use high-cardinality labels (user IDs, timestamps)
  • Don't skip middleware application
  • Don't expose sensitive data in labels

πŸ“Š Example PromQL Queries

# Request rate (requests per second)
rate(http_requests_total[1m])

# Average request duration
rate(http_request_duration_ms_sum[5m]) / rate(http_request_duration_ms_count[5m])

# 95th percentile latency
histogram_quantile(0.95, rate(http_request_duration_ms_bucket[5m]))

# Error rate
sum(rate(http_requests_total{status=~"5.."}[1m])) / sum(rate(http_requests_total[1m]))

# Active requests
http_active_requests

πŸ› οΈ Tech Stack

  • OpenTelemetry - Observability framework
  • Prometheus - Metrics storage and querying
  • Jaeger - Distributed tracing backend
  • Grafana - Metrics visualization
  • Node.js - Runtime environment
  • Express - Web framework (example)

πŸ“¦ Package Versions

{
  "@opentelemetry/api": "^1.7.0",
  "@opentelemetry/sdk-node": "^0.211.0",
  "@opentelemetry/sdk-metrics": "^1.18.0",
  "@opentelemetry/exporter-prometheus": "^0.48.0",
  "@opentelemetry/exporter-trace-otlp-http": "^0.211.0",
  "@opentelemetry/auto-instrumentations-node": "^0.69.0",
  "@opentelemetry/resources": "^1.18.0",
  "@opentelemetry/semantic-conventions": "^1.18.0"
}

πŸ› Troubleshooting

No metrics appearing

  1. Check middleware is applied: app.use(middleware)
  2. Generate traffic to your API
  3. Verify endpoint: curl http://localhost:9464/metrics

Port already in use

Change the port in configuration:

initMetrics({ port: 9465 })

Metrics not in Prometheus

Check Prometheus scrape configuration targets your service:

- targets: ['api:9464']  # or 'localhost:9464'

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“ License

MIT License - feel free to use this in your projects!

πŸ™ Acknowledgments

πŸ“§ Contact

For questions and support, please open an issue on GitHub.


Made with ❀️ for the Node.js community

Drop this module into any API and get instant observability! πŸš€

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages