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
-
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/otelyarn add @opentelemetry/sdk-node \@opentelemetry/auto-instrumentations-node \@opentelemetry/exporter-trace-otlp-http \@opentelemetry/resources \@opentelemetry/semantic-conventions \@fastify/otel -
Setup auto-instrumentation using OpenTelemetry
Create a file named
instrumentation.jsin your project:// instrumentation.jsconst 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 utilityconst 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}`,);// Configurationconst 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 SDKconst 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 APItry {sdk.start();logger.info("Tracing initialized successfully");} catch (error) {logger.error("Failed to initialize tracing", error);}// Gracefully shut down the SDK on process exitprocess.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"); -
Import Instrumentation in Your Application
This script must be imported at the application’s entry point. For instance, if you have
server.jsas 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:
- Set up Trace Provider with the application’s name as Service Name.
- Set up OTLP Exporter with Last9 OTLP endpoint.
- 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:
- Start your Fastify application
- Make some requests to your application
- Log into your Last9 account to confirm traces are being received
Need Help?
If you encounter any issues or have questions:
- Join our Discord community for real-time support
- Contact our support team at support@last9.io