OpenTelemetry Setup in a Nodejs Application
OpenTelemetry can auto-instrument many common modules for a Javascript application. The telemetry data captured can then be sent to SigNoz for analysis and visualization.
OpenTelemetry is a set of tools, APIs, and SDKs used to instrument applications to create and manage telemetry data(Logs, metrics, and traces). For any distributed system based on microservice architecture, it's an operational challenge to solve performance issues quickly.
Telemetry data helps engineering teams to troubleshoot issues across services and identify the root causes. In other words, telemetry data powers observability for your distributed applications.
Steps to get started with OpenTelemetry for a Nodejs application:
- Installing SigNoz
- Creating sample Nodejs app
- Set up OpenTelemetry and send data to SigNoz
Installing SigNoz
You can get started with SigNoz using just three commands at your terminal.
git clone -b main https://github.com/SigNoz/signoz.git
cd signoz/deploy/
./install.sh
For detailed instructions, you can visit our documentation.
When you are done installing SigNoz, you can access the UI at: http://localhost:3301
The application list shown in the dashboard is from a sample app called HOT R.O.D that comes bundled with the SigNoz installation package.
Creating sample Nodejs application
You need to ensure that you have Node.js version 12 or newer. You can download the latest version of Node.js here. For the sample application, let's create a basic 'hello world' express.js application.
If you do not want to follow these steps manually, you can directly check out the GitHub repo of the sample application. You can run the app directly after cloning it and start sending data to SigNoz. The code is already instrumented with OpenTelemetry libraries.
But, it would be better if you follow these steps to understand what's happening.
Check if node is installed on your machine by using the below command:
node -v
Steps to get the app set up and running:
Make a directory and install express
Make a directory for your sample app on your machine. Then open up the terminal, navigate to the directory path and install express with the following command:npm i express
Create index.js
Create a file calledindex.js
in your directory and with any text editor setup your 'Hello World' file with the code below:const express = require("express");
const cors = require('cors')
const PORT = process.env.PORT || "5555";
const app = express();
app.use(cors());
app.use(express.json())
app.all("/", (req, res) => {
res.json({ method: req.method, message: "Hello World", ...req.body });
});
app.get('/404', (req, res) => {
res.sendStatus(404);
})
app.listen(parseInt(PORT, 10), () => {
console.log(`Listening for requests on http://localhost:${PORT}`);
})Check if your application is working
Run your application by using the below command at your terminal.node index.js
You can check if your app is working by visiting: http://localhost:5555/
Once you are finished checking, exit the application by using
Ctrl + C
on your terminal.
Set up OpenTelemetry and send data to SigNoz
Install OpenTelemetry packages
You will need the following OpenTelemetry packages for this sample application.npm install --save @opentelemetry/sdk-node
npm install --save @opentelemetry/auto-instrumentations-node
npm install --save @opentelemetry/exporter-trace-otlp-httpThe dependencies included are briefly explained below:
@opentelemetry/sdk-node
- This package provides the full OpenTelemetry SDK for Node.js including tracing and metrics.@opentelemetry/auto-instrumentations-node
- This module provides a simple way to initialize multiple Node instrumentations.@opentelemetry/exporter-trace-otlp-http
- This module provides the exporter to be used with OTLP (http/json
) compatible receivers.
Create
tracing.js
file
Instantiate tracing by creating atracing.js
file and using the below code.// tracing.js
'use strict'
const process = require('process');
const opentelemetry = require('@opentelemetry/sdk-node');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http');
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');
const exporterOptions = {
url: 'http://localhost:4318/v1/traces'
}
const traceExporter = new OTLPTraceExporter(exporterOptions);
const sdk = new opentelemetry.NodeSDK({
traceExporter,
instrumentations: [getNodeAutoInstrumentations()],
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'node_app'
})
});
// initialize the SDK and register with the OpenTelemetry API
// this enables the API to record telemetry
sdk.start()
// gracefully shut down the SDK on process exit
process.on('SIGTERM', () => {
sdk.shutdown()
.then(() => console.log('Tracing terminated'))
.catch((error) => console.log('Error terminating tracing', error))
.finally(() => process.exit(0));
});OpenTelemetry Node SDK currently does not detect the
OTEL_RESOURCE_ATTRIBUTES
from.env
files as of today. That’s why we need to include the variables in thetracing.js
file itself.About environment variables:
service_name
: name of the service you want to monitorenvironment
: dev, prod, staging, etc.http://localhost:4318/v1/traces
is the default url for sending your tracing data. We are assuming you have installed SigNoz on yourlocalhost
. Based on your environment, you can update it accordingly. It should be in the following format:http://<IP of SigNoz backend>:4318/v1/traces
noteRemember to allow incoming requests to port 4318 of machine where SigNoz backend is hosted.
Run your application
Now when you run your application, OpenTelemetry captures telemetry data from it and send it to SigNoz.node -r ./tracing.js index.js
You can check your application running at http://localhost:5555/. You need to generate some load in order to see data reported on SigNoz dashboard. Refresh the endpoint for 10-20 times, and wait for 2-3 mins.
And, congratulations! You have instrumented your sample Node.js app. You can now access the SigNoz dashboard at http://localhost:3301 to monitor your app for performance metrics.
Metrics, Traces and Logs of the Nodejs application
SigNoz makes it easy to visualize metrics and traces captured through OpenTelemetry instrumentation.
SigNoz comes with out of box RED metrics charts and visualization. RED metrics stands for:
- Rate of requests
- Error rate of requests
- Duration taken by requests
You can then choose a particular timestamp where latency is high to drill down to traces around that timestamp.
You can use flamegraphs to exactly identify the issue causing the latency.
You can also use SigNoz for log management. For Nodejs applications, you can use the winston logger to send logs to SigNoz.
Conclusion
OpenTelemetry makes it very convenient to instrument your Nodejs application. You can then use an open-source APM tool like SigNoz to analyze the performance of your app. As SigNoz offers a full-stack observability tool, you don't have to use multiple tools for your monitoring needs.
You can try out SigNoz by visiting its GitHub repo 👇
If you face any issues while trying out SigNoz, feel free to write to us at: support@signoz.io
If you want to read more about SigNoz 👇