Prometheus - empty cluster metrics in express server

85 views Asked by At

I have multiple workers when I try to access clusterMetrics from aggregatorRegistry, showing empty data in the /metrics endpoint. I tried using the express-prom-bundle library. but It didn't work.

const express = require('express');
const cluster = require('cluster');
const os = require('os');
const { 
    AggregatorRegistry, register,
    collectDefaultMetrics, 
    Counter
} = require('prom-client');

const app = express();
const PORT = 3000;

// Create an AggregatorRegistry to collect metrics across all workers
const aggregatorRegistry = new AggregatorRegistry();

// Register the aggregatorRegistry with the default metrics
collectDefaultMetrics({ register, aggregatorRegistry });

// Middleware to expose metrics endpoint
app.get('/metrics', async (req, res) => {
    try {
        const metrics = await aggregatorRegistry.clusterMetrics();
        res.set('Content-Type', aggregatorRegistry.contentType);
        res.end(metrics);
    } catch (err) {
        console.error('Error collecting metrics:', err);
        res.status(500).end();
    }
  });

app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

if (cluster.isMaster) {
  // Fork workers equal to the number of CPU cores
  const numCPUs = os.cpus().length;
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  // Log worker process IDs
  cluster.on('online', (worker) => {
    console.log(`Worker ${worker.process.pid} is online`);
  });

  // Handle worker exits
  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died with code ${code} and signal ${signal}`);
    // Replace the dead worker
    cluster.fork();
  });
} else {
    let counter = new Counter({
        name: "test_counter",
        help: "Test",
        labelNames: ["worker"]
    });

    setInterval(async () => {
        console.log((await counter.get()).values);
        counter.labels(process.pid).inc();
    }, 5000);
  // Start the Express server in each worker
  app.listen(PORT, () => {
    console.log(`Worker ${process.pid} listening on port ${PORT}`);
  });
}

I'm able to access the register.metrics() from each worker. but the aggregation of them is not working. can you please help me to fix this?

0

There are 0 answers