@fastify/otel

OpenTelemetry auto-instrumentation library.
Install
npm i @fastify/otel
Usage
@fastify/otel works as a metric creator as well as application performance monitor for your Fastify application.
It must be configured before defining routes and other plugins in order to cover the most of your Fastify server.
- It automatically wraps the main request handler
- Instruments all route hooks (defined at instance and route definition level)
onRequest
preParsing
preValidation
preHandler
preSerialization
onSend
onResponse
onError
- Instruments automatically custom 404 Not Found handler
Example:
const FastifyOtelInstrumentation = require('@fastify/otel');
const fastifyOtelInstrumentation = new FastifyOtelInstrumentation({ servername: '<yourCustomApplicationName>' });
fastifyOtelInstrumentation.setTracerProvider(provider)
module.exports = { fastifyOtelInstrumentation }
const { fastifyOtelInstrumentation } = require('./otel.js');
const Fastify = require('fastify');
const app = fastify();
await app.register(fastifyOtelInstrumentation.plugin());
app.get('/', () => 'hello world')
app.addHook('onError', () => )
app.register((instance, opts, done) => {
instance.register(fastifyOtelInstrumentation.plugin());
app.get('/', () => 'hello world')
}, { prefix: '/nested' })
Automatic plugin registration
The plugin can be automatically registered with registerOnInitialization option set to true.
In this case, it is necessary to await fastify instance.
const fastifyOtelInstrumentation = new FastifyOtelInstrumentation({
registerOnInitialization: true,
});
const Fastify = require('fastify');
const app = await fastify();
Notes:
- This instrumentation requires
@opentelemetry/instrumentation-http to be able to propagate the traces all the way back to upstream
- The HTTP instrumentation might cover all your routes although
@fastify/otel just covers a subset of your application
For more information about OpenTelemetry, please refer to the OpenTelemetry JavaScript documentation.
APIs
FastifyOtelRequestContext
The FastifyOtelRequestContext is a wrapper around the OpenTelemetry Context and Tracer APIs. It also provides a way to manage the context of a request and its associated spans as well as some utilities to extract and inject further traces from and to the trace carrier.
const { fastifyOtelInstrumentation } = require('./otel.js');
const Fastify = require('fastify');
const app = fastify();
await app.register(fastifyOtelInstrumentation.plugin());
app.get('/', (req, reply) => {
const { context, tracer, span, inject, extract } = req.opentelemetry();
const parentCxt = extract(req.headers);
const newSpan = tracer.startSpan('my-new-span', {
parent: parentCxt,
});
newSpan.end();
const carrier = {};
inject(carrier);
reply.headers(carrier);
return 'hello world';
});
License
Licensed under MIT.