OpenTelemetry for JavaScript | Honeycomb

We use cookies or similar technologies to personalize your online experience & tailor marketing to you. Many of our product features require cookies to function properly.

Read our privacy policy I accept cookies from this site

OpenTelemetry for JavaScript

OpenTelemetry for JavaScript can be used to add automatic and manual instrumentation to your applications and have trace data sent to Honeycomb. Automatic instrumentation is enabled by adding instrumentation packages. Manual instrumentation can be added using the OpenTelemetry API.

Requirements 

These instructions will explain how to set up automatic and manual instrumentation for a Node.js service. In order to follow along, you will need:

  • Node.js version 8.5.0 or newer.
  • A NodeJS application.
  • A Honeycomb API Key. You can find your API key in your Environment Settings. If you do not have an API key yet, sign up for a free Honeycomb account.

Automatic Instrumentation 

Install Modules 

In your terminal, run the commands below to install the packages required to auto-instrument a Node.js application:

npm install --save \
    @opentelemetry/sdk-node \
    @opentelemetry/exporter-trace-otlp-proto \
    @opentelemetry/auto-instrumentations-node

auto-instrumentations-node is a meta package that provides a way to initialize multiple Node.js instrumentations like express, dns, http, and more. Alternatively, you can install individual instrumentation packages.

In your terminal, run the commands below to install the packages required to auto-instrument a Node.js application:

yarn add \
    @opentelemetry/sdk-node \
    @opentelemetry/exporter-trace-otlp-proto \
    @opentelemetry/auto-instrumentations-node

auto-instrumentations-node is a meta package that provides a way to initialize multiple Node.js instrumentations like express, dns, http, and more. Alternatively, you can install individual instrumentation packages.

Initialize 

Create an initialization file, commonly known as the tracing.js file, and import it as the first step in your application lifecycle. Alternatively, include this initialization file with the -r, --require Node.js CLI option.

// tracing.js
'use strict';

const { NodeSDK } = require('@opentelemetry/sdk-node');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { OTLPTraceExporter } = require("@opentelemetry/exporter-trace-otlp-proto");

// The Trace Exporter exports the data to Honeycomb and uses
// the environment variables for endpoint, service name, and API Key.
const traceExporter = new OTLPTraceExporter();

const sdk = new NodeSDK({
  traceExporter,
  instrumentations: [getNodeAutoInstrumentations()]
});

sdk.start()

Configure and Run 

Configure OpenTelemetry to send events to Honeycomb using environment variables.

The header x-honeycomb-team is your API key. Your service name will be used as the Service Dataset in Honeycomb, which is where data is stored. The service name is specified by OTEL_SERVICE_NAME.

export OTEL_EXPORTER_OTLP_ENDPOINT="https://api.honeycomb.io"
export OTEL_EXPORTER_OTLP_HEADERS="x-honeycomb-team=your-api-key"
export OTEL_SERVICE_NAME="your-service-name"

Run the Node.js app with the OpenTelemetry initialization file to generate data:

node -r ./tracing.js APPLICATION_MAIN_FILE.js

If you are a Honeycomb Classic user, the Dataset also must be specified using the x-honeycomb-dataset header. A Dataset is a bucket where data gets stored in Honeycomb.

export OTEL_EXPORTER_OTLP_HEADERS="x-honeycomb-team=your-api-key,x-honeycomb-dataset=your-dataset"

gRPC Instead of HTTP 

To use gRPC instead of HTTP, install the packages, update the traceExporter, and update the endpoint:

npm install --save @grpc/grpc-js \
    @opentelemetry/exporter-trace-otlp-grpc
yarn add @grpc/grpc-js \
    @opentelemetry/exporter-trace-otlp-grpc
// tracing.js
const { NodeSDK } = require("@opentelemetry/sdk-node");
const {
  getNodeAutoInstrumentations,
} = require("@opentelemetry/auto-instrumentations-node");
const {
  OTLPTraceExporter,
} = require("@opentelemetry/exporter-trace-otlp-grpc");
const { credentials } = require("@grpc/grpc-js");

const traceExporter = new OTLPTraceExporter({
  credentials: credentials.createSsl(),
});
let sdk = new NodeSDK({
  traceExporter,
  instrumentations: [getNodeAutoInstrumentations()],
});

sdk.start();
export OTEL_EXPORTER_OTLP_ENDPOINT=api.honeycomb.io:443

Adding Manual Instrumentation 

Auto-instrumentation is the easiest way to get started with instrumenting your code, but in order to get the most insight into your system, you should add manual instrumentation where appropriate. To do this, use the OpenTelemetry API to access the currently executing span and add attributes to it, and/or to create new spans.

To add manual instrumentation, you need to add the OpenTelemetry API package:

npm install --save @opentelemetry/api
yarn add @opentelemetry/api

Adding Attributes to Spans 

It is often beneficial to add attributes to a currently executing span in a trace. For example, you may have an application or service that handles users, and you want to associate the user with the span when querying your service in Honeycomb. In order to do this, get the current span from the context and set an attribute with the user ID:

const opentelemetry = require("@opentelemetry/api");

function handleUser(user) {
  let activeSpan = opentelemetry.trace.getActiveSpan();
  activeSpan.setAttribute("user.id", user.getId());
}

This will add a user.id field to the current span so that you can use the field in WHERE, GROUP BY or ORDER clauses in the Honeycomb query builder.

Initialize a Tracer 

To start manually tracing, you must initialize a tracer. This is typically done once per file. The string passed to getTracer appears in the library.name attribute in all spans created from that tracer.

const opentelemetry = require("@opentelemetry/api");

const tracer = opentelemetry.trace.getTracer("my-service-tracer");

You can then use this tracer to create custom spans.

Creating New Spans 

Auto-instrumentation can show the shape of requests to your system, but only you know the really important parts. In order to get the full picture of what is happening, you will have to add manual instrumentation and create some custom spans. To do this, grab the tracer from the OpenTelemetry API:

const opentelemetry = require("@opentelemetry/api");

const tracer = opentelemetry.trace.getTracer("my-service-tracer");

function runQuery() {
  tracer.startActiveSpan("expensive-query", (span) => {
    // ... do cool stuff
    span.end();
  });
}

More on Manual Instrumentation 

The OpenTelemetry documentation for JavaScript has a comprehensive set of topics on manual instrumentation.

Sampling 

npm install --save @opentelemetry/core
yarn add @opentelemetry/core
// tracing.js
const { TraceIdRatioBasedSampler } = require("@opentelemetry/core");

const sdk = new NodeSDK({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: "<YOUR_SERVICE_NAME>",
    SampleRate: 2,
  }),
  traceExporter,
  instrumentations: [getNodeAutoInstrumentations()],
  sampler: new TraceIdRatioBasedSampler(0.5),
});

You can configure the OpenTelemetry SDK to sample the data it generates. Honeycomb re-weights sampled data, so it is recommended that you set a resource attribute containing the sample rate.

In the example above, our goal is to keep approximately half (1/2) of the data volume. The resource attribute contains the denominator (2), while the OpenTelemetry sampler argument contains the decimal value (0.5).

If you have multiple services that communicate with each other, it is important that they have the same sampling configuration. Otherwise, each service might make a different sampling decision, resulting in incomplete or broken traces. You can sample using a standalone proxy as an alternative, like Honeycomb Refinery, or when you have more robust sampling needs.

Distributed Trace Propagation 

When a service calls another service, you want to ensure that the relevant trace information is propagated from one service to the other. This allows Honeycomb to connect the two services in a trace.

Distributed tracing enables you to trace and visualize interactions between multiple instrumented services. For example, your users may interact with a front-end API service, which talks to two internal APIs to fulfill their request. In order to have traces connect spans for all these services, it is necessary to propagate trace context between these services, usually by using an HTTP header.

Both the sending and receiving service must use the same propagation format, and both services must be configured to send data to the same Honeycomb dataset.

Endpoint URLs for OTLP/HTTP 

When using the OTEL_EXPORTER_OTLP_ENDPOINT environment variable with an SDK and an HTTP exporter, the final path of the endpoint is actually modified by the SDK to represent the specific signal being sent.

For example, when exporting trace data, the endpoint is updated to append v1/traces. When exporting metrics data, the endpoint is updated to append v1/metrics. The same modification is not necessary for gRPC.

By setting OTEL_EXPORTER_OTLP_ENDPOINT to https://api.honeycomb.io, traces are sent to https://api.honeycomb.io/v1/traces and metrics to https://api.honeycomb.io/v1/metrics.

export OTEL_EXPORTER_OTLP_ENDPOINT=https://api.honeycomb.io

If the desired outcome is to send data to a different endpoint depending on the signal, use OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT instead of the more generic OTEL_EXPORTER_OTLP_ENDPOINT.

When using a signal-specific environment variable, these paths must be appended manually. Set OTEL_EXPORTER_OTLP_TRACES_ENDPOINT for traces, appending the endpoint with v1/traces, and OTEL_EXPORTER_OTLP_METRICS_ENDPOINT for metrics, appending the endpoint with v1/metrics.

Send both traces and metrics to Honeycomb using this method by setting the following variables:

export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.honeycomb.io/v1/traces
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://api.honeycomb.io/v1/metrics

More details about endpoints and signals can be found in the OpenTelemetry Specification.

Troubleshooting 

No Traces for a Service 

The service name is a required configuration value. If it is unspecified, all trace data will be sent to a default dataset called unknown_service.

Debug Level Logging 

If you have completed configuration and still do not see traces, there may be errors that you cannot see. By default, the OpenTelemetry exporters do not print errors. To help troubleshoot, try changing your OpenTelemetry exporter’s log level. In your tracing initialization file, add this code before your configuration:

// tracing.js

const opentelemetry = require("@opentelemetry/api");
opentelemetry.diag.setLogger(
  new opentelemetry.DiagConsoleLogger(),
  opentelemetry.DiagLogLevel.WARN
);

Then, try again and look for output.

If the logger still does not print enough, try increasing the log level by replacing WARN with DEBUG in opentelemetry.DiagLogLevel.WARN.

Exporting to the Console 

If you have checked for errors but your data is not in Honeycomb as expected, use a ConsoleSpanExporter to print your spans to the console. This will help confirm whether your app is being instrumented with the data you expect.

npm install --save @opentelemetry/sdk-trace-base
yarn add @opentelemetry/sdk-trace-base

Import the ConsoleSpanExporter and temporarily replace the OTLPTraceExporter:

const { ConsoleSpanExporter } = require("@opentelemetry/sdk-trace-base");

const traceExporter = new ConsoleSpanExporter();

The auto-instrumentation uses a BatchSpanProcessor for exporting telemetry, which is often the recommendation when working in production. For debugging purposes, it can be helpful to instead use a SimpleSpanProcessor for more immediate feedback. The SimpleSpanProcessor immediately forwards ended spans to the exporter, whereas the BatchSpanProcessor batches and sends them in bulk.

To swap out processors, additional configuration is needed, including a swap from the NodeSDK to NodeTracerProvider and two additional dependencies:

npm install --save @opentelemetry/instrumentation
npm install --save @opentelemetry/sdk-trace-node
yarn add @opentelemetry/instrumentation
yarn add @opentelemetry/sdk-trace-node
const { NodeTracerProvider } = require("@opentelemetry/sdk-trace-node");
const {
  ConsoleSpanExporter,
  SimpleSpanProcessor,
} = require("@opentelemetry/sdk-trace-base");
const { registerInstrumentations } = require("@opentelemetry/instrumentation");

// export to console for debugging
const traceExporter = new ConsoleSpanExporter();

// NodeTracerProvider instead of NodeSDK
const provider = new NodeTracerProvider({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: "<YOUR_SERVICE_NAME>",
  }),
});
// use SimpleSpanProcessor with ConsoleSpanExporter
provider.addSpanProcessor(new SimpleSpanProcessor(traceExporter));
// register the global tracer provider
provider.register();

// add the same auto-instrumentations used with the Node SDK
registerInstrumentations({
  instrumentations: [getNodeAutoInstrumentations()],
});

Keep in mind that printing to the console should only be used for debugging purposes. It is not recommended for production.

OTLP Protobuf Definitions 

Honeycomb supports receiving telemetry data via OpenTelemetry’s native protocol, OTLP, over gRPC, HTTP/protobuf, and HTTP/JSON. The minimum supported versions of OTLP protobuf definitions are 0.7.0 for traces and metrics.

If the protobuf version in use by the SDK does not match a supported version by Honeycomb, a different version of the SDK may need to be used. If the SDK’s protobuf version is older than the minimum supported version, and telemetry is not appearing as expected in Honeycomb, upgrade the SDK to a version with the supported protobuf definitions. If using an added dependency on a proto library, ensure the version of protobuf definitions matches the supported version of the SDK.

Receiving 464 Errors 

You may receive a 464 error response from the Honeycomb API when sending telemetry using gRPC and HTTP1. The gRPC format depends on using HTTP2 and any request over HTTP1 will be rejected by the Honeycomb servers.

Missing .proto Files Error 

If your application builds using a bundler, like Webpack or ESBuild, or if your application uses TypeScript, you will see an error that says that a specific .proto file is not found:

opentelemetry/proto/collector/trace/v1/trace_service.proto not found in any of the include paths <directory>/protos

This error appears because the .proto files are not imported or required by the library that uses them, so bundlers do not know to include them in the final build. There are two ways to work around this error:

Copy the /protos Directory to the Correct Location 

Modify the bundler configuration to copy the /protos directory from the library to the same level as the build directory:

const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
  ... other config ...
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "./node_modules/@opentelemetry/otlp-grpc-exporter-base/build/protos/**/*",
          to: "./protos"
        }
      ],
    }),
  ],
};
const { copy } = require('esbuild-plugin-copy')

require('esbuild').build({
  ... other config ...
  plugins: [
    copy({
      resolveFrom: 'cwd',
      assets: {
        from: ['./node_modules/@opentelemetry/otlp-grpc-exporter-base/build/protos/**/*'],
        to: ['./protos'],
        keepStructure: true
      },
    }),
  ],
}).catch(() => process.exit(1));

TypeScript configuration currently cannot specify which extra files to copy for your build. In this case, use a postbuild npm script to copy the proto files to the correct location.

Use the HTTP/JSON Trace Exporter With a Collector 

In order to send HTTP/JSON data to Honeycomb, configure an OpenTelemetry Collector. Then, configure the Node app with @opentelemetry/exporter-trace-otlp-http to send data to the Collector, which will send it to Honeycomb.

// tracing.js
const { NodeSDK } = require("@opentelemetry/sdk-node");
const {
  getNodeAutoInstrumentations,
} = require("@opentelemetry/auto-instrumentations-node");
const {
  OTLPTraceExporter,
} = require("@opentelemetry/exporter-trace-otlp-http");

const traceExporter = new OTLPTraceExporter({
  // optional - url default value is http://localhost:4318/v1/traces
  url: "<your-collector-endpoint>:4318/v1/traces",
});
let sdk = new NodeSDK({
  traceExporter,
  instrumentations: [getNodeAutoInstrumentations()],
});

sdk.start();

Did you find what you were looking for?