Skip to content
Last9 named a Gartner Cool Vendor in AI for SRE Observability for 2025! Read more →
Last9

Fastify

Send traces to Last9 from Fastify applications using OpenTelemetry

Use OpenTelemetry to instrument your JavaScript Fastify application and send telemetry data to Last9. This integration provides automatic instrumentation for your Fastify web framework.

Prerequisites

Install OpenTelemetry Packages

Install the required OpenTelemetry instrumentation packages:

npm install --save @opentelemetry/sdk-node \
@opentelemetry/auto-instrumentations-node \
@opentelemetry/exporter-trace-otlp-http \
@opentelemetry/resources \
@opentelemetry/semantic-conventions \
@fastify/otel

Setup Auto-instrumentation

  1. Create instrumentation file

    Create a file named instrumentation.js in your project root:

    // instrumentation.js
    const opentelemetry = 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, ATTR_DEPLOYMENT_ENVIRONMENT } = require('@opentelemetry/semantic-conventions');
    const FastifyOtelInstrumentation = require('@fastify/otel');
    // Initialize the Fastify OpenTelemetry instrumentation
    const fastifyOtelInstrumentation = new FastifyOtelInstrumentation({
    registerOnInitialization: true
    });
    // Simple logging utility
    const logger = {
    info: (message) => console.log(`[OpenTelemetry] ${message}`),
    error: (message, error) => console.error(`[OpenTelemetry Error] ${message}`, error || '')
    };
    logger.info(`Initializing OpenTelemetry for service: ${process.env.OTEL_SERVICE_NAME}`);
    // Configuration
    const LAST9_ENDPOINT = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "$last9_otlp_endpoint";
    const LAST9_AUTH = process.env.OTEL_EXPORTER_OTLP_HEADERS || "$last9_basic_auth_header";
    // Create and configure SDK
    const sdk = new opentelemetry.NodeSDK({
    resource: resourceFromAttributes({
    [ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || 'fastify-app',
    [ATTR_DEPLOYMENT_ENVIRONMENT]: process.env.NODE_ENV || 'development',
    }),
    traceExporter: new OTLPTraceExporter({
    url: `${LAST9_ENDPOINT}/v1/traces`,
    headers: {
    Authorization: LAST9_AUTH,
    },
    }),
    instrumentations: [
    getNodeAutoInstrumentations({
    '@opentelemetry/instrumentation-fs': { enabled: false },
    }),
    ],
    });
    // Initialize the SDK and register with the OpenTelemetry API
    try {
    sdk.start();
    logger.info('Tracing initialized successfully');
    } catch (error) {
    logger.error('Failed to initialize tracing', error);
    }
    // Gracefully shut down the SDK on process exit
    process.on('SIGTERM', () => {
    logger.info('Application shutting down, finalizing traces');
    sdk.shutdown()
    .then(() => logger.info('Trace provider shut down successfully'))
    .catch((error) => logger.error('Error shutting down trace provider', error))
    .finally(() => process.exit(0));
    });
    process.on('SIGINT', () => {
    logger.info('Application shutting down (SIGINT), finalizing traces');
    sdk.shutdown()
    .then(() => logger.info('Trace provider shut down successfully'))
    .catch((error) => logger.error('Error shutting down trace provider', error))
    .finally(() => process.exit(0));
    });
    logger.info('OpenTelemetry instrumentation setup complete');
  2. Import instrumentation

    Import the instrumentation at the very top of your main application file (e.g., server.js or app.js):

    // Import this BEFORE any other imports
    require('./instrumentation');
    // Now import your application code
    const fastify = require('fastify')({ logger: true });
    // Your application code continues...
  3. Set environment variables

    Set the following environment variables for your application:

    export OTEL_SERVICE_NAME="your-fastify-service"
    export OTEL_EXPORTER_OTLP_ENDPOINT="$last9_otlp_endpoint"
    export OTEL_EXPORTER_OTLP_HEADERS="authorization=$last9_basic_auth_header"
    export NODE_ENV="production"

    Replace $last9_otlp_endpoint and $last9_basic_auth_header with the values from your Last9 integration settings.

Verification

Start your application

node server.js

You should see OpenTelemetry initialization messages in your console:

[OpenTelemetry] Initializing OpenTelemetry for service: your-fastify-service
[OpenTelemetry] Tracing initialized successfully
[OpenTelemetry] OpenTelemetry instrumentation setup complete

Generate traces

Make some requests to your Fastify application endpoints to generate trace data.

View traces in Last9

  1. Log in to your Last9 dashboard
  2. Navigate to the Traces section
  3. Filter by your service name
  4. Traces should appear within 1-2 minutes

Troubleshooting

If traces are not appearing:

  1. Check your environment variables are set correctly
  2. Verify the instrumentation import is at the very top of your entry file
  3. Enable debug logging by adding this to your instrumentation file:
    const { diag, DiagConsoleLogger, DiagLogLevel } = require("@opentelemetry/api");
    diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
  4. Check console output for OpenTelemetry error messages
  5. Verify network connectivity to the Last9 OTLP endpoint

For additional support, reach out to Last9 support at support@last9.io.

Next Steps