Skip to content
Last9
Book demo

Fastify

Monitor Fastify applications with OpenTelemetry instrumentation for comprehensive performance tracking

Use OpenTelemetry to instrument your JavaScript Fastify application and send telemetry data to Last9. You can either run OpenTelemetry Collector or send the telemetry directly from the application.

Prerequisites

Before setting up Fastify monitoring, ensure you have:

  • Node.js 16.0 or higher
  • Fastify application
  • Last9 account with integration credentials
  1. Install Instrumentation Packages

    Install the following packages:

    npm install --save \
    @opentelemetry/api@1.9.0 \
    @opentelemetry/auto-instrumentations-node@0.59.0 \
    @opentelemetry/exporter-trace-otlp-http@0.201.1 \
    @opentelemetry/resources@2.0.1 \
    @opentelemetry/sdk-node@0.201.1 \
    @opentelemetry/sdk-trace-base@2.0.1 \
    @opentelemetry/semantic-conventions@1.34.0 \
    @fastify/otel
  2. Setup auto-instrumentation using OpenTelemetry

    Create a file named instrumentation.js in your project:

    // instrumentation.js
    const { NodeSDK } = require('@opentelemetry/sdk-node');
    const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
    const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http');
    const { resourceFromAttributes } = require('@opentelemetry/resources');
    const { ATTR_SERVICE_NAME } = require('@opentelemetry/semantic-conventions');
    const { BatchSpanProcessor } = require('@opentelemetry/sdk-trace-base');
    const api = require('@opentelemetry/api');
    const FastifyOtelInstrumentation = require('@fastify/otel');
    // Initialize the Fastify OpenTelemetry instrumentation.
    const fastifyOtelInstrumentation = new FastifyOtelInstrumentation({ registerOnInitialization: true });
    // For troubleshooting, uncomment the following lines to enable OpenTelemetry debug logging:
    // const { diag, DiagConsoleLogger, DiagLogLevel } = require('@opentelemetry/api');
    // diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
    // BaggageSpanProcessor - propagates W3C Baggage entries as span attributes for RUM correlation
    class BaggageSpanProcessor {
    onStart(span, parentContext) {
    const baggage = api.propagation.getBaggage(parentContext || api.context.active());
    if (!baggage) return;
    for (const [key, entry] of baggage.getAllEntries()) {
    span.setAttribute(key, entry.value);
    }
    }
    onEnd() {}
    forceFlush() { return Promise.resolve(); }
    shutdown() { return Promise.resolve(); }
    }
    // Create and configure SDK
    // SDK auto-reads OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_EXPORTER_OTLP_HEADERS from env
    const sdk = new NodeSDK({
    resource: resourceFromAttributes({
    [ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME,
    'deployment.environment': process.env.NODE_ENV,
    }),
    spanProcessors: [
    new BaggageSpanProcessor(),
    new BatchSpanProcessor(new OTLPTraceExporter()),
    ],
    instrumentations: [
    getNodeAutoInstrumentations({
    '@opentelemetry/instrumentation-fs': { enabled: false },
    }),
    ],
    });
    // sdk.start() is synchronous in sdk-node 0.201.x+
    try {
    sdk.start();
    console.log('[OpenTelemetry] Fastify instrumentation initialized');
    } catch (error) {
    console.error('[OpenTelemetry] Failed to initialize tracing', error);
    }
    process.on('SIGTERM', () => sdk.shutdown().finally(() => process.exit(0)));
    process.on('SIGINT', () => sdk.shutdown().finally(() => process.exit(0)));
  3. Import Instrumentation in Your Application

    This script must be imported at the application’s entry point. For instance, if you have server.js as your entry file, then import it at the top of the file as follows:

    require("./instrumentation");

How it Works

The above code performs the following steps:

  1. Set up Trace Provider with the application’s name as Service Name.
  2. Set up OTLP Exporter with Last9 OTLP endpoint.
  3. Set up auto instrumentation.

Once you run the Node.js application, it will start sending telemetry data to Last9.

Verification

To verify the setup is working:

  1. Start your Fastify application
  2. Make some requests to your application
  3. Log into your Last9 account to confirm traces are being received

Need Help?

If you encounter any issues or have questions: