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
- Last9 cluster created
- Obtain your OTLP endpoint and auth header: https://app.last9.io/integrations/
- Node.js Fastify application
- NPM or Yarn package manager
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/otelSetup Auto-instrumentation
-
Create instrumentation file
Create a file named
instrumentation.jsin your project root:// 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 instrumentationconst fastifyOtelInstrumentation = new FastifyOtelInstrumentation({registerOnInitialization: true});// 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 = 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 SDKconst 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 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
Import the instrumentation at the very top of your main application file (e.g.,
server.jsorapp.js):// Import this BEFORE any other importsrequire('./instrumentation');// Now import your application codeconst fastify = require('fastify')({ logger: true });// Your application code continues... -
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_endpointand$last9_basic_auth_headerwith the values from your Last9 integration settings.
Verification
Start your application
node server.jsYou should see OpenTelemetry initialization messages in your console:
[OpenTelemetry] Initializing OpenTelemetry for service: your-fastify-service[OpenTelemetry] Tracing initialized successfully[OpenTelemetry] OpenTelemetry instrumentation setup completeGenerate traces
Make some requests to your Fastify application endpoints to generate trace data.
View traces in Last9
- Log in to your Last9 dashboard
- Navigate to the Traces section
- Filter by your service name
- Traces should appear within 1-2 minutes
Troubleshooting
If traces are not appearing:
- Check your environment variables are set correctly
- Verify the instrumentation import is at the very top of your entry file
- Enable debug logging by adding this to your instrumentation file:
const { diag, DiagConsoleLogger, DiagLogLevel } = require("@opentelemetry/api");diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
- Check console output for OpenTelemetry error messages
- Verify network connectivity to the Last9 OTLP endpoint
For additional support, reach out to Last9 support at support@last9.io.