Skip to content

@metrics/emitter

This module makes it possible stream metrics over a socket to a daemon. The socket can be of different protocols (UDP, TCP etc) but the data trasmitted over it is expected to be of the @metrics/metric type.

For recieving metrics over a socket one are expected to use the @metrics/daemon module.

The main purpose of this is to be able to send metrics from multiple processes to a sentral service (daemon) for further handling.

Usage

Terminal window
npm install @metrics/emitter

Set up an emitter which connects to a daemon on UDP on port 6000 and pipes the metrics from the @metrics/client:

const Emitter = require('@metrics/emitter');
const Client = require('@metrics/client');
const emitter = new Emitter('udp', { port: 6000 });
const client = new Client();
client.pipe(emitter);

Here is a simplified example of each worker in a cluster pushing metrics to the master and the master pushing the metric further:

const master = () => {
const daemon = new Daemon('udp', { port: 6000 });
const client = new Client();
daemon.pipe(client);
daemon.listen();
};
const worker = () => {
const emitter = new Emitter('udp', { port: 6000 });
const client = new Client();
client.pipe(emitter);
client.metric({
name: `worker_${cluster.worker.id}`,
description: `Worker number: ${cluster.worker.id}`,
value: 1,
});
};
const workers = [];
if (cluster.isMaster) {
for (let i = 0; i < (os.cpus().length - 1); i++) {
workers.push(cluster.fork());
}
master();
}
if (cluster.isWorker) {
worker();
}

See the cluster example in daemon for a full example.

API

constructor(options)

Create a new Emitter instance.

const Emitter = require('@metrics/emitter');
const emitter = new Emitter(transport, options);

transport (required)

What type of transport to use. Supported values are:

  • udp - For UDP transport.

options (optional)

An Object containing misc configuration for the selected transport. Please see each transport for which option which can be passed in.

returns

Returns a Writable stream in object mode.

Transports

The following transports is supported:

UDP

UDP as a transport can be enabled by providing udp to the transport argument on the Emitter constructor. The UDP transport takes the following options (passed to the options argument on the Emitter constructor):

  • port - Number - The port of the daemon. Default: 40400.
  • address - String - The address of the daemon. Default: localhost.