OpenTelemetry With Fastify

Traces, Metrics, Logs — Standardized

OpenTelemetry With Fastify

Wire Fastify into the OpenTelemetry ecosystem so you can correlate traces, metrics, and logs across services and ship them to any compatible backend.

4 min read Level 3/5 #fastify#opentelemetry#observability
What you'll learn
  • Install the OpenTelemetry SDK and Fastify instrumentation
  • Configure an OTLP exporter
  • Read trace context from request hooks

OpenTelemetry is the vendor-neutral standard for traces, metrics, and logs. The OTel Node SDK auto-instruments common libraries — including Fastify — so most apps get distributed tracing with under twenty lines of setup.

Install

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

Bootstrapping

OTel must be initialised before importing Fastify so instrumentation can hook into module loaders.

// tracing.ts
import { NodeSDK } from '@opentelemetry/sdk-node'
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'

const sdk = new NodeSDK({
  serviceName: 'web-api',
  traceExporter: new OTLPTraceExporter({ url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT }),
  instrumentations: [getNodeAutoInstrumentations()],
})

sdk.start()
node --import ./tracing.js dist/index.js

Reading the Trace ID

Add the active trace ID to your logs so any log line links back to a trace.

import { trace } from '@opentelemetry/api'

app.addHook('onRequest', async (req) => {
  const span = trace.getActiveSpan()
  if (span) {
    req.log = req.log.child({ trace_id: span.spanContext().traceId })
  }
})

Export to an OTel Collector and fan out to Jaeger, Tempo, Datadog, or Honeycomb. You wrote your app once; choose your backend later.

Clustering & Multi-Core →