Skip to Content
Xeonr Developer Docs

Node.js

Send traces, metrics and logs from a Node.js server or script to Lantern with the OpenTelemetry Node SDK, automatic instrumentation and pino, over OTLP/HTTP.

A Node.js process sends to Lantern with the standard OpenTelemetry Node SDK. Load it before your application, and every instrumented library reports through it with no changes to your code:

  • http and fetch;
  • Express, Fastify and Koa;
  • the database drivers;
  • pino and winston.

Lantern's add-on, @lntrn/otel, starts that SDK for you. It doesn't replace the SDK: it runs the stock NodeSDK and OTLP exporters and adds Lantern's endpoint, credential and resource attributes. Without it, the SDK reads the same things from OTEL_* variables (below).

Before you start

  • Node.js 22.15 or newer, which @opentelemetry/sdk-node 0.300 requires. The examples are ES modules ("type": "module").
  • An edge credential for your organisation (see Server telemetry).

Checked with Node.js 24, @opentelemetry/sdk-node 0.300.0, @opentelemetry/auto-instrumentations-node 0.82.0, pino 10 and @lntrn/otel 0.1.0.

Already on OpenTelemetry? Add this

npm install @lntrn/otel @opentelemetry/api @opentelemetry/auto-instrumentations-node pino
export OTEL_SERVICE_NAME=checkout-api
export LNTRN_EDGE_USER=<org>.<id>       # the edge credential's username
export LNTRN_EDGE_PASSWORD=…            # and its password
export LNTRN_NAMESPACE=checkout LNTRN_ENVIRONMENT=dev
node --import @lntrn/otel/register server.mjs

That replaces your instrumentation.mjs. Before the app loads, @lntrn/otel/register:

  • starts a stock NodeSDK with the OTLP/HTTP protobuf exporters for traces, metrics and logs, to https://otlp.lntrn.dev with the credential as HTTP Basic;
  • turns on @opentelemetry/auto-instrumentations-node when it is installed, with fs off;
  • registers OpenTelemetry's ES module hook, so pino, express and the rest are instrumented when imported as ES modules;
  • flushes before the process exits: when the event loop empties, and on SIGTERM or SIGINT.

OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES work as in every SDK. OTEL_LOGS_EXPORTER=none (or …TRACES…, …METRICS…) turns a signal off. In a container, put the flag in the image: CMD ["node", "--import", "@lntrn/otel/register", "server.mjs"], or NODE_OPTIONS="--import @lntrn/otel/register".

Starting NodeSDK yourself? setup() takes the same settings as options, plus instrumentations and anything else NodeSDK takes:

instrumentation.mjs
import { register } from "node:module";
import { setup } from "@lntrn/otel";
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";

register("@opentelemetry/instrumentation/hook.mjs", import.meta.url);
const lantern = setup({ serviceName: "checkout-api", instrumentations: [getNodeAutoInstrumentations()] });
process.once("SIGTERM", () => lantern.shutdown().finally(() => process.exit(0)));

Where it sends depends on what is set: an edge credential sends to the edge, a device token (LNTRN_DEVICE_TOKEN, or token in setup) to the client ingest (see Devices), and LNTRN_ENDPOINT alone to that collector. With none of them, it leaves the plain OTEL_EXPORTER_OTLP_* variables in charge.

Without the add-on

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

Export the OTEL_EXPORTER_OTLP_* variables from Server telemetry, and set up the SDK yourself.

Set up the SDK

The SDK has to start before anything it instruments is imported, so it lives in its own module and is loaded with --import:

instrumentation.mjs
// Loaded before the app with `node --import ./instrumentation.mjs`.
import { register } from "node:module";
import { NodeSDK } from "@opentelemetry/sdk-node";
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";

// Lets the instrumentations patch ES modules (pino, express, …) as they load.
register("@opentelemetry/instrumentation/hook.mjs", import.meta.url);

// Exporters, endpoint, headers and resource all come from OTEL_* variables:
// OTLP/HTTP traces, metrics and logs to OTEL_EXPORTER_OTLP_ENDPOINT.
const sdk = new NodeSDK({
  instrumentations: [getNodeAutoInstrumentations({
    // Noisy and rarely useful.
    "@opentelemetry/instrumentation-fs": { enabled: false },
  })],
});
sdk.start();

for (const signal of ["SIGTERM", "SIGINT"]) {
  process.once(signal, () => sdk.shutdown().finally(() => process.exit(0)));
}

With no exporters given, the SDK exports traces, metrics and logs over OTLP to OTEL_EXPORTER_OTLP_ENDPOINT, with the headers in OTEL_EXPORTER_OTLP_HEADERS (the Basic credential), as protobuf over HTTP. It takes service.name and the other resource attributes from OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES (see Server telemetry).

A server

Nothing in the application refers to OpenTelemetry. The HTTP instrumentation makes a server span per request, and the pino instrumentation adds the trace to every log line and exports it:

server.mjs
import http from "node:http";
import pino from "pino";

const logger = pino();

const server = http.createServer(async (req, res) => {
  logger.info({ path: req.url }, "handling request");
  res.end("ok\n");
});
server.listen(8080, () => logger.info("listening on :8080"));
export OTEL_SERVICE_NAME=checkout-api
export OTEL_RESOURCE_ATTRIBUTES=service.namespace=checkout,service.version=1.4.2,deployment.environment.name=dev
node --import @lntrn/otel/register server.mjs   # or --import ./instrumentation.mjs without the add-on

Your own spans and metrics

Use @opentelemetry/api anywhere in the application; the SDK started by --import serves it:

app.mjs
import { trace, metrics, SpanStatusCode } from "@opentelemetry/api";
import pino from "pino";

const logger = pino();
const tracer = trace.getTracer("example");
const jobs = metrics.getMeter("example").createCounter("example.jobs");

await tracer.startActiveSpan("process-batch", async (span) => {
  for (let i = 0; i < 3; i++) {
    jobs.add(1);
    logger.info({ item: i }, "processed item");
  }
  await fetch("https://example.com/");
  const err = new Error("upstream timed out");
  span.recordException(err);
  span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
  logger.error({ err }, "batch failed");
  span.end();
});

process.kill(process.pid, "SIGTERM"); // flush and exit; a server would just keep running

logger.error({ err }, …) records the error's type, message and stack as exception.type, exception.message and exception.stacktrace. A short script must let the SDK shut down before it exits, or the last batch is lost. @lntrn/otel/register flushes on SIGTERM and when the event loop empties. Without it, the SIGTERM handler in instrumentation.mjs does.

Logs: stdout or OTLP

The setup above exports logs over OTLP, which is right for a VM, a laptop, a CI job or anything else outside Kubernetes.

In a Kubernetes cluster running Lantern's agent, keep logging to stdout and turn the export off:

export OTEL_LOGS_EXPORTER=none

pino still writes trace_id and span_id into every line, and the agent reads every container's output, so each line is collected once and still opens its trace. pino's numeric levels (30, 50) become info and error. With both on, every line is stored twice.

Verify

Start the server, make a request, then within a minute:

lntrn --org <org> query traces 'service.name:checkout-api' --since 15m
lntrn --org <org> query logs 'service.name:checkout-api' --since 15m

Or open Traces in the console at https://<org>.lntrn.dev and filter by service.name. Each request is a GET span, and its log line carries the same trace id.

If nothing arrives:

  • check the credential with the curl in Server telemetry;
  • set OTEL_LOG_LEVEL=debug to see the exporters' errors;
  • check that --import @lntrn/otel/register (or ./instrumentation.mjs) is on the command line. Without it the API is a no-op and nothing complains.

Browsers and devices

Code that runs in a browser or on someone else's device can't hold an edge credential. See Browsers and React and Devices.

A Node process on hardware you don't control (a kiosk, an emulation node, an Electron main process) sends to a client project with a device token instead. Give @lntrn/otel a function that fetches one:

setup({ serviceName: "emulation-node", token: () => fetchTokenFromYourBackend() });

It is cached until shortly before its exp, with one fetch shared between exports. This is @lntrn/device/otel's TokenCache, the same one the JavaScript device add-on uses.

On this page