OTel For Node.js
In this guide, we will walk you through the process of setting up and using OpenTelemetry in Node.js. You will learn how to instrument a simple application to produce traces, metrics, and logs.
Step 1: Prerequisites
Before diving into OpenTelemetry, be sure that you have the following installed:
Step 2: Example Application
For this tutorial, we will be using a basic Express application. However, OpenTelemetry JavaScript is compatible with other web frameworks like Koa and Nest.JS as well. Feel free to adapt the instructions to your preferred framework.
Step 3: Installation
- Set up an empty package.json in a new directory:
2. Install Express dependencies
3. Create and launch an HTTP Server by creating a file named app.js (app.ts, if you are using TypeScript) and adding the following code to it:
4. Run the application using the following command then open http://localhost:8080/rolldice in your web browser:
Step 4: Instrumentation
To install the instrumentation packages, we will use the auto-instrumentations-node package. It automatically creates spans corresponding to code called in libraries. 1. Use the following command to install the Node SDK auto-instrumentaion andexporter packages.
2. The instrumentation setup and configuration are required to run before the application code. We will use the --require flag for this task.
3. Create a file named instrumentation.js (instrumentation.ts if you are using TypeScript) and add the following setup code to it:
The exporter URL mentioned above, along with the KloudMate API-Key as the Authorization header will send the data to KloudMate.
Step 5: Run the Instrumented App
1. Run the instrumented application and use the --require flag to load the instrumentation before the application code.
2. Open http://localhost:8080/rolldice in your web browser. You should see spans on the Traces page in your KloudMate account.
Source URL for the example application: https://opentelemetry.io/docs/instrumentation/js/getting-started/nodejs/