npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@lggutierrez/monitoring

v1.0.4

Published

Prometheus monitoring library for Node.js and Express applications

Readme

@lggutierrez/monitoring

Librería ligera de monitoreo con Prometheus para aplicaciones Node.js y Express. Configuración simple, uso inmediato.

Características

Configuración en 2 líneas - Importa y usa, sin instancias manuales
📊 Métricas completas - HTTP, sistema, PM2
🎯 Zero-config - Funciona out-of-the-box
🔧 Altamente configurable - Personaliza lo que necesites
📦 Ligero - ~13KB comprimido
🚀 TypeScript First - Tipado completo

Instalación

npm install @lggutierrez/monitoring
# o
pnpm add @lggutierrez/monitoring

Uso Rápido

import express from 'express';
import { createMonitoringMiddleware, createMonitoringRouter } from '@lggutierrez/monitoring';

const app = express();

// ¡Eso es todo! Solo 2 líneas
app.use(createMonitoringMiddleware());
app.use(createMonitoringRouter());

app.listen(3000);
// ✅ Métricas en: http://localhost:3000/monitoring/metrics
// ✅ Info en: http://localhost:3000/monitoring/info

Uso Avanzado

Con Configuración Personalizada

import express from 'express';
import { createMonitoringMiddleware, createMonitoringRouter } from '@lggutierrez/monitoring';

const app = express();

// Middleware con configuración
app.use(createMonitoringMiddleware({
  ignoreRoutes: ['/health', '/admin/*'],
  collectDefaultMetrics: true,
  histogramBuckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5],
}));

// Router con configuración
app.use(createMonitoringRouter({
  basePath: '/metrics',
  defaultFormat: 'json', // o 'text'
}));

app.listen(3000);

Endpoints Expuestos

GET /monitoring/metrics

Métricas de Prometheus. Soporta dos formatos:

Formato texto (default):

curl http://localhost:3000/monitoring/metrics
# o
curl http://localhost:3000/monitoring/metrics?format=text

Formato JSON:

curl http://localhost:3000/monitoring/metrics?format=json

GET /monitoring/info

Información de la aplicación y host en JSON:

curl http://localhost:3000/monitoring/info
{
  "up": true,
  "application": {
    "name": "my-app",
    "version": "1.0.0",
    "description": "My application"
  },
  "host": {
    "hostname": "server-01",
    "platform": "linux",
    "arch": "x64",
    "ipAddresses": ["192.168.1.100"]
  },
  "pm2": {
    "enabled": true,
    "processId": "0",
    "instanceId": "0"
  },
  "timestamp": "2025-12-04T20:00:00.000Z"
}

API

createMonitoringMiddleware(options?)

Crea el middleware de Express que captura métricas HTTP.

Parámetros:

  • options? - Configuración opcional del servicio de monitoreo

Opciones disponibles:

interface MonitoringMiddlewareOptions {
  /** Rutas a ignorar. Soporta wildcards (*) */
  ignoreRoutes?: string[];  // Default: ['/monitoring/metrics', '/monitoring/info']
  
  /** Buckets del histograma en segundos */
  histogramBuckets?: number[];  // Default: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
  
  /** Habilitar métricas del sistema (CPU, memoria, GC) */
  collectDefaultMetrics?: boolean;  // Default: true
  
  /** Ruta al package.json */
  packageJsonPath?: string;  // Default: '../../package.json'
}

Ejemplo:

app.use(createMonitoringMiddleware({
  ignoreRoutes: ['/health', '/admin/*'],
  histogramBuckets: [0.1, 0.5, 1, 2, 5],
}));

createMonitoringRouter(options?)

Crea un router de Express con endpoints de métricas.

Parámetros:

  • options? - Configuración del router y servicio

Opciones disponibles:

interface MonitoringRouterOptions {
  /** Ruta base para los endpoints */
  basePath?: string;  // Default: '/monitoring'
  
  /** Formato por defecto de las métricas */
  defaultFormat?: 'text' | 'json';  // Default: 'text'
  
  // + todas las opciones de MonitoringMiddlewareOptions
}

Ejemplos:

// Default: /monitoring/metrics y /monitoring/info
app.use(createMonitoringRouter());

// Custom path: /health/metrics y /health/info
app.use(createMonitoringRouter({ basePath: '/health' }));

// Formato JSON por defecto
app.use(createMonitoringRouter({ defaultFormat: 'json' }));

Métricas disponibles

HTTP Metrics

  • http_request_duration_seconds - Histograma de duración de requests
  • http_requests_total - Contador total de requests HTTP
  • http_requests_active - Gauge de requests activos
  • http_request_errors_total - Contador de errores HTTP
  • http_requests_time - Gauge de requests por hora

Labels

Todas las métricas incluyen labels como:

  • method - Método HTTP (GET, POST, etc.)
  • route - Ruta de la petición
  • status_code - Código de estado HTTP
  • status_class - Clase de estado (2xx, 3xx, 4xx, 5xx)
  • error_type - Tipo de error (cuando aplica)

Métricas por defecto

Cuando collectDefaultMetrics: true:

  • CPU usage
  • Memory usage
  • Event loop lag
  • Garbage collection
  • Process info

Endpoints recomendados

/metrics

Endpoint en formato Prometheus para scraping

app.get('/metrics', async (req, res) => {
  res.set('Content-Type', 'text/plain');
  res.send(await monitoringService.getMetricsAsText());
});

/app-info

Información de la aplicación y host

app.get('/app-info', (req, res) => {
  res.json(monitoringService.getAppInfo());
});

Configuración de Prometheus

Agregar en prometheus.yml:

scrape_configs:
  - job_name: 'my-app'
    scrape_interval: 15s
    static_configs:
      - targets: ['localhost:3000']
    metrics_path: '/metrics'

Soporte PM2

La librería detecta automáticamente si está corriendo bajo PM2 y expone información adicional:

  • Process ID
  • Instance ID
  • Process name

TypeScript

La librería está completamente tipada y exporta todos los tipos necesarios:

import type {
  MonitoringConfig,
  PrometheusMetrics,
  AppInfo,
  MetricLabels,
} from '@your-org/prometheus-monitoring';

Seguridad

Versiones exactas en producción

Usa versiones exactas en tu package.json:

{
  "dependencies": {
    "@your-org/prometheus-monitoring": "1.0.0"
  }
}

Proteger endpoints

Recuerda proteger tus endpoints de métricas en producción:

app.get('/metrics', authMiddleware, async (req, res) => {
  res.set('Content-Type', 'text/plain');
  res.send(await monitoringService.getMetricsAsText());
});

License

MIT