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

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/sdk-node \
    @opentelemetry/auto-instrumentations-node \
    @opentelemetry/exporter-trace-otlp-http \
    @opentelemetry/resources \
    @opentelemetry/semantic-conventions \
    @fastify/otel
  2. Setup auto-instrumentation using OpenTelemetry

    Create a file named instrumentation.js in your project:

    // 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. This will register the instrumentation automatically on the Fastify server.
    const fastifyOtelInstrumentation = new FastifyOtelInstrumentation({
    registerOnInitialization: true,
    });
    // Enable logging for OpenTelemetry if needed for debugging
    // const { diag, DiagConsoleLogger, DiagLogLevel } = require("@opentelemetry/api");
    // diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
    // 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 = "{{ .Logs.WriteURL }}/v1/traces";
    const LAST9_AUTH = "{{ .Logs.AuthValue }}";
    const SERVICE_NAME = "<your-service-name>"; // Replace with your service name
    // Create and configure SDK
    const sdk = new opentelemetry.NodeSDK({
    resource: resourceFromAttributes({
    [ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME,
    [ATTR_DEPLOYMENT_ENVIRONMENT]: process.env.NODE_ENV,
    }),
    traceExporter: new OTLPTraceExporter({
    url: LAST9_ENDPOINT,
    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");
  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: