Skip to content

Instrument a Node.js App

This guide walks you through the process of instrumenting a Node.js application using zero-code OpenTelemetry for collecting traces, metrics, logs, and monitoring using Kloudmate. Zero-code instrumentation enables you to capture telemetry from many popular libraries and frameworks without modifying your application code.

Before you begin, ensure you have the following installed:

For demonstration, we will be using a basic Express application. You can adapt this to other frameworks like Koa or Nest.js if needed.

1. Set up an empty package.json in a new directory:

npm init -y

2. Install Express and dependencies:

npm install express
npm install @opentelemetry/auto-instrumentations-node

3. Create and run an HTTP Server Create a file named app.js (or app.ts if you’re using TypeScript) and add the following code to set up a simple HTTP server:

/*app.js*/
const express = require('express');

const PORT = parseInt(process.env.PORT || '8080');
const app = express();

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

app.get('/rolldice', (req, res) => {
  res.send(getRandomNumber(1, 6).toString());
});

app.listen(PORT, () => {
  console.log(`Listening for requests on http://localhost:${PORT}`);
});

Set these variables in your shell environment before starting the app.

export OTEL_TRACES_EXPORTER="otlp"
export OTEL_METRICS_EXPORTER="otlp"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://otel.kloudmate.com:4318"
export OTEL_EXPORTER_OTLP_HEADERS="authorization=YOUR_PRIVATE_KEY"
export OTEL_NODE_RESOURCE_DETECTORS="env,host,os"
export OTEL_NODE_DISABLED_INSTRUMENTATIONS="fs,dns,net"
export OTEL_SERVICE_NAME="your-service-name"
export NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register"
$ node app.js
Listening for requests on http://localhost:8080

Open localhost:8080/rolldice in your web browser to verify. Now you should see spans on the Traces page in your KloudMate account.

NameMetrics
nodejs_eventloop_delay_minEvent loop minimum delay.
nodejs_eventloop_delay_maxEvent loop maximum delay.
nodejs_eventloop_delay_meanEvent loop mean delay.
nodejs_eventloop_delay_stddevEvent loop standard deviation delay.
nodejs_eventloop_delay_p50Event loop 50 percentile delay.
nodejs_eventloop_delay_p90Event loop 90 percentile delay.
nodejs_eventloop_delay_p99Event loop 99 percentile delay.
nodejs_eventloop_utilizationEvent loop utilization.
nodejs_eventloop_timeCumulative duration of time the event loop has been in each state.
nodejs_eventloop_stateThe state of event loop time.