Monitoring your Nestjs application using OpenTelemetry
Tags: nestjs, javascript, monitoring, microservices
Published: 2021-12-27 13:20:31

Nestjs is a Nodejs framework for building scalable server-side applications with typescript. It makes use of frameworks like Express and Fastify to enable rapid development. It has gained wide popularity in recent times, and many applications are making use of the Nestjs framework.

Monitoring your Nestjs application is critical for performance management. But setting up monitoring for Nestjs applications can get cumbersome requiring multiple libraries and patterns. That's where Opentelemetry comes in.

OpenTelemetry is the leading open-source standard for instrumenting your code to generate telemetry data that can be a one-stop solution for monitoring Nestjs applications.

OpenTelemetry is a set of tools, APIs, and SDKs used to instrument applications to create and manage telemetry data(Logs, metrics, and traces). It aims to make telemetry data(logs, metrics, and traces) a built-in feature of cloud-native software applications.

 One of the biggest advantages of using OpenTelemetry is that it is vendor-agnostic. It can export data in multiple formats, which you can send to a backend of your choice.

In this article, we will use [SigNoz](https://signoz.io/) as a backend. SigNoz is an open-source APM tool that can be used for both metrics and distributed tracing.

Let's get started and see how to use OpenTelemetry for a Nestjs application.

## Running a Nestjs application with OpenTelemetry
First, you need to install SigNoz. Data collected by OpenTelemetry will be sent to SigNoz for storage and visualization.

### Installing SigNoz
You can get started with SigNoz using just three commands at your terminal.

```jsx
git clone https://github.com/SigNoz/signoz.git
cd signoz/deploy/
./install.sh
```
For detailed instructions, you can visit our documentation.

[![Deployment Docs](https:/signoz.io/img/blog/common/deploy_docker_documentation.webp)](https://signoz.io/docs/deployment/docker/?utm_source=blog&utm_medium=opentelemetry_nestjs)

If you have installed SigNoz on your local host, you can access the UI at: [http://localhost:3000](http://localhost:3000/application)

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.

![SigNoz dashboard showing application list](https:/signoz.io/img/blog/2021/08/signoz_dashboard_hc.webp)<figcaption>SigNoz Dashboard</figcaption>

### Instrumenting a sample Nestjs application with OpenTelemetry
For instrumenting a Nestjs application with OpenTelemetry, you need to install the required OpenTelemetry packages first. Steps involved in instrumenting a Nestjs application with OpenTelemetry are as follows:

**Install below dependencies<br></br>**

```jsx
npm install --save @opentelemetry/api
npm install --save @opentelemetry/sdk-node
npm install --save @opentelemetry/auto-instrumentations-node
npm install --save @opentelemetry/exporter-trace-otlp-proto@0.27.0
```

<br></br>

**Create a `tracer.ts` file**<br></br>
The `IP of SIgNoz` will be localhost if you are running SigNoz on local.
   
```jsx
// tracing.ts

'use strict'

const opentelemetry = require('@opentelemetry/sdk-node');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-proto');
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');

// configure the SDK to export telemetry data to the console
// enable all auto-instrumentations from the meta package
const exporterOptions = {
  url: 'http://<IP of SigNoz>:55681/v1/trace',
 }
const traceExporter = new OTLPTraceExporter(exporterOptions);
const sdk = new opentelemetry.NodeSDK({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: 'sampleNestJsApp'
  }),
  traceExporter,
  instrumentations: [getNodeAutoInstrumentations()]
});

// initialize the SDK and register with the OpenTelemetry API
// this enables the API to record telemetry
sdk.start()
  .then(() => console.log('Tracing initialized'))
  .catch((error) => console.log('Error initializing tracing', error));

// 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));
});

module.exports = sdk 
```

<br></br>

**Import the tracer module where your app starts**<br></br>
On `main.ts` file or file where your app starts import tracer using below command:
```jsx
const tracer = require('./tracer')
```

<br></br>

**Start the tracer**<br></br>
```jsx
await tracer.start();
```

<br></br>


You can now run your Nestjs application. The data captured with OpenTelemetry from your application should start showing on the SigNoz dashboard.

You can check out a sample Nestjs application already instrumented with OpenTelemetry here:

[Sample Nestjs Application](https://github.com/SigNoz/sample-NestJs-app)

If you run this app, you can find a `SampleNestJsApp` in the list of applications monitored with SigNoz.

![Sample Nestjs application in the list of applications monitored by SigNoz](https:/signoz.io/img/blog/2021/12/nestjs_signoz_dashboard.webp)<figcaption>Sample Nestjs application in the list of applications monitored by SigNoz</figcaption>

## Open-source tool to visualize telemetry data
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

![SigNoz charts and metrics](https:/signoz.io/img/blog/common/signoz_charts_application_metrics.webp)<figcaption>Measure things like application latency, requests per sec, error percentage and see your top endpoints with SigNoz.</figcaption>

You can then choose a particular timestamp where latency is high to drill down to traces around that timestamp.

![List of traces on SigNoz dashboard](https:/signoz.io/img/blog/common/signoz_list_of_traces_hc.webp)<figcaption>View of traces at a particular timestamp</figcaption>

You can use flamegraphs to exactly identify the issue causing the latency.

![Flamegraphs used to visualize spans of distributed tracing in SigNoz UI](https:/signoz.io/img/blog/common/signoz_flamegraphs.webp)<figcaption>View of traces at a particular timestamp</figcaption>

You can also build custom metrics dashboard for your infrastructure.

![Custom metrics dashboard](https:/signoz.io/img/blog/common/signoz_custom_dashboard-min.webp)<figcaption>You can also build a custom metrics dashboard for your infrastructure</figcaption>


## Conclusion
OpenTelemetry makes it very convenient to instrument your Nestjs 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 👇

[![SigNoz GitHub repo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8yroh39ngk6sz6tv3z9y.png)](https://bit.ly/2WkkmL4)

If you have any questions or need any help in setting things up, join our slack community and ping us in `#help` channel.

[![SigNoz Slack community](https:/signoz.io/img/blog/common/join_slack_cta.png)](https://bit.ly/signoz-slack)

---

If you want to read more about SigNoz 👇

[Golang Aplication Monitoring with OpenTelemetry and SigNoz](https://signoz.io/opentelemetry/go/)

[OpenTelemetry collector - complete guide](https://signoz.io/blog/opentelemetry-collector-complete-guide/)