Instrument a Node.js application

Instrument a Node.js application

If you need process-level telemetry for Node.js, use this guide to set up the upstream OpenTelemetry SDK for JavaScript for Application Observability.

Grafana Labs recommends setting up OpenTelemetry components, including instrumentation and an OpenTelemetry Collector distribution, using one of the Grafana Cloud onboarding workflows. These opinionated guides make it easy to get started and include all the binaries, configuration, and connection parameters you need to set up OpenTelemetry for Grafana Cloud.

Install the SDK

Before you begin, ensure you have a Node.js development environment with a package manager such as NPM or Yarn, and a Node.js application to instrument.

Run the following command in your project folder:

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

Run your application

Run your application with the following command to use auto-instrumentation and export OTLP data:

sh
OTEL_TRACES_EXPORTER="otlp" \
OTEL_METRICS_EXPORTER="otlp" \
OTEL_LOGS_EXPORTER="otlp" \
OTEL_NODE_RESOURCE_DETECTORS="env,host,os" \
OTEL_RESOURCE_ATTRIBUTES="service.name=<name>,service.namespace=<namespace>,deployment.environment=<environment>" \
OTEL_EXPORTER_OTLP_ENDPOINT=<endpoint> \
NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register" \
node <my-app>.js

Replace variables in <...> with values specific to your application and backend. For more details, see the OpenTelemetry service attributes documentation.

  • <name>: your service name, for example, shoppingcart
  • <namespace>: a string to group related services, such as ecommerce for a team that manages several services
  • <environment>: the deployment environment, for example, the production deployment tier

Some backends, such as Grafana Cloud, also require you to set authentication headers in the OTEL_EXPORTER_OTLP_HEADERS environment variable.

Resources

  1. OpenTelemetry JavaScript documentation
  2. @opentelemetry/api on NPM
  3. opentelemetry-js on GitHub