How to Use OpenTelemetry & JavaScript Together: A Tutorial

Navigate to:

This post was written by Siddhant Varma. Scroll down for the author’s bio.

Observability is an essential aspect of a healthy software architecture and a highly performant system. It enables developers and engineers to understand and dive deeper into how their application behaves. This in turn helps them monitor it effectively. Every engineer or IT professional wants an efficient and reliable system that can give them data and insights about how to reduce their system’s downtime, make it more efficient, enhance its overall user experience, etc.

However, to achieve effective observability, you need a dedicated tool based on the observability framework that provides logs, metrics, and traces about your system. OpenTelemetry is one such popular tool based on the observability framework. In this post, we’ll walk you through what OpenTelemetry is, what it’s used for, and how you can use it in a JavaScript application.

What is OpenTelemetry? What is it used for?

OpenTelemetry is a popular software tool used for adding observability to your application. It’s open source, so there’s no vendor lock-in for your application’s health data, giving you full control over that data. You can use OpenTelemetry to generate, collect, analyze, and export telemetry data.

It’s important that you understand what telemetry data comprises. Any information related to your system that tells you about the operation, performance, and usage of your system is referred to as telemetry data. Telemetry data often helps you understand why your system is not performing as expected. It comprises three components: logs, traces, and metrics. Logs are data from your application that help you debug it when something doesn’t work as intended. Metrics include any quantitative data around your throughput, memory utilization, CPU usage, and so on. Traces contain details about all the incoming and outgoing requests from your system.

red-box

Since OpenTelemetry is technology and framework-agnostic, you can integrate it with any type of application built using any language, framework, or technology.

Using OpenTelemetry with JavaScript

Let’s look at how you can use OpenTelemetry in a JavaScript project. For this, we’ll work with a simple Node.js and Express app.

Setup

Create a new directory for your Node.js project:

mkdir opentelemetry-js

Then navigate inside this project and create a new Express project using Express Generator:

cd opentelemetry-js && npx express-generator

Next, install all the required dependencies inside this project:

npm i

That should create a boilerplate Express app for you. Great! Now go ahead and install some dependencies from OpenTelemetry JS. You can use the Node SDK to add OpenTelemetry to your Node.js application. Run the following installation commands:

npm install --save @opentelemetry/api
npm install --save @opentelemetry/sdk-node
npm install --save @opentelemetry/auto-instrumentations-node

Once you do that, all the required dependencies for adding OpenTelemetry to your Node.js and Express application will be added to your project.

Add OpenTelemetry tracing

Now create a file in the root directory called tracing.js with the following code:

// tracing.js

'use strict'

const process = require('process');
const opentelemetry = require('@opentelemetry/sdk-node');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { ConsoleSpanExporter } = require('@opentelemetry/sdk-trace-base');
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 traceExporter = new ConsoleSpanExporter();
const sdk = new opentelemetry.NodeSDK({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: 'my-service',
  }),
  traceExporter,
  instrumentations: [getNodeAutoInstrumentations()]
});

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

In the above code, we import the relevant modules from the OpenTelemetry packages we installed. Then we configure the Node SDK to export telemetry data to the console. We initialize the Node SDK and enable the OpenTelemetry API to record telemetry data.

Now let’s run the Node.js application using the following:

npm run start

That should run your Node.js application on port 3000:

run Node-js

If You now visit http://localhost:3000, you should see the following Express app:

welcome to Express

Let’s see what happens when we make a curl request to http://localhost:3000:

curl request

On your terminal where your Node app is running, you should see a request sent to the URL:

request sent

Now let’s start OpenTelemetry when we run our NodeJS app. For that, we’ll make the following changes to the package.json file and update your start script with the following:

"scripts": {
"start": "node -r ./tracing.js ./bin/www"
},

Now when you run your Node.js application, OpenTelemetry should start collecting and exporting telemetry data for your app. Hit the request again to the same URL. This time you should see telemetry data on the console/terminal:

telemetry data

You can further send this data to a telemetry data analyzing tool.

What’s the difference between OpenTelemetry SDK and OpenTelemetry API?

When you work with OpenTelemetry, there are two main components involved: the OpenTelemetry SDK and an OpenTelemetry API. Both provide relevant libraries and interfaces that help you add OpenTelemetry to your application and collect telemetry data.

OpenTelemetry API

The OpenTelemetry API provides you with a set of interfaces and methods that you can use to generate telemetry data. It provides a standard way to define and collect metrics, logs, and traces from your code written in a certain framework. Additionally, it provides a standard set of attributes and metadata. When you add this metadata to your telemetry data, you can derive more meaning from it thanks to contextual information. Note that the OpenTelemetry API is the generic set of interfaces that are not dependent on any technology, programming language, or framework.

OpenTelemetry SDK

The OpenTelemetry SDK is a set of libraries and tools that implement the OpenTelemetry API. It provides some additional functionality for generating and processing telemetry data. The SDK includes a set of default instrumentation for popular libraries and frameworks, such as HTTP clients and servers, as well as support for custom instrumentation. It also provides features such as batching, sampling, and exporting to different backends. You used the Node.js SDK in your JavaScript application above. The OpenTelemetry SDK will be specific to the technology or framework you’re using in your application.

Is OpenTelemetry push or pull?

You’ve seen in depth what OpenTelemetry is and how you can use it. Now we’ll cover how it works under the hood.

Push model

Basically, there are two models on which telemetry data is collected and processed. The first is the push model, where telemetry data is generated by your application or service. This telemetry data is then sent to a telemetry back end for further processing. The telemetry backend helps you analyze the data and make sense of it.

Pull model

The second model is the pull model, where telemetry data is received or pulled from various sources like the OpenTelemetry SDK and is then sent to a telemetry data monitoring platform or a logging service. This data can also be filtered, transformed, or aggregated before being sent to the destination.

OpenTelemetry supports both the push and pull models. The SDK provides exporters that allow telemetry data to be sent to various backends, including log aggregation systems, tracing systems, and metrics systems. The telemetry data can be sent immediately or batched and sent periodically.

When you need real-time telemetry data, the push model is the best option. When you need telemetry data to be sourced from various places and then aggregated for processing and analysis, you can opt for the pull model. OpenTelemetry’s support for both models provides flexibility and enables organizations to choose the telemetry data collection and export strategy that best fits their needs.

Is OpenTelemetry ready for production?

OpenTelemetry may be new, but it’s enjoying early adoption. It’s flexible and open source, and organizations can easily tailor it to their software architecture and use cases. Being technology-agnostic, it supports a wide range of software and applications. Developers working on all types of technology can use it to collect, analyze, and export telemetry data.

A large community of developers and contributors are actively working on it, and they’re backed by the Cloud Native Computing Foundation (CNCF). The foundation also provides support and resources for understanding, learning, and developing on top of OpenTelemetry. It has terrific documentation, and you can safely use it in production.

But be careful how you configure OpenTelemetry in a production environment. Be sure to rigorously test and validate the telemetry data. You also need to ensure that the data is properly collected, processed, and exported to the relevant telemetry backend for further processing.

About the author

This post was written by Siddhant Varma. Siddhant is a full stack JavaScript developer with expertise in frontend engineering. He’s worked with scaling multiple startups in India and has experience building products in the Ed-Tech and healthcare industries. Siddhant has a passion for teaching and a knack for writing. He’s also taught programming to many graduates, helping them become better future developers.