@@ -12,6 +12,7 @@ import {
1212import type { IntegrationFn , Span } from '@sentry/core' ;
1313import { generateInstrumentOnce } from '../../otel/instrument' ;
1414import { FastifyInstrumentationV3 } from './fastify-v3/instrumentation' ;
15+ import * as diagnosticsChannel from 'node:diagnostics_channel' ;
1516
1617import type { FastifyInstance } from './fastify-v3/internal-types' ;
1718import { DEBUG_BUILD } from '../../debug-build' ;
@@ -41,12 +42,22 @@ export const instrumentFastifyV3 = generateInstrumentOnce(
4142 } ) ,
4243) ;
4344
44- let fastifyOtelInstrumentationInstance : FastifyOtelInstrumentation | undefined ;
45-
4645export const instrumentFastify = generateInstrumentOnce ( INTEGRATION_NAME , ( ) => {
4746 // FastifyOtelInstrumentation does not have a `requestHook`
4847 // so we can't use `addFastifySpanAttributes` here for now
49- fastifyOtelInstrumentationInstance = new FastifyOtelInstrumentation ( ) ;
48+ const fastifyOtelInstrumentationInstance = new FastifyOtelInstrumentation ( ) ;
49+ const plugin = fastifyOtelInstrumentationInstance . plugin ( ) ;
50+
51+ diagnosticsChannel . subscribe ( 'fastify.initialization' , message => {
52+ const fastifyInstance = ( message as { fastify ?: FastifyInstance } ) . fastify ;
53+
54+ fastifyInstance ?. register ( plugin ) . after ( err => {
55+ if ( err ) {
56+ DEBUG_BUILD && logger . error ( 'Failed to setup Fastify instrumentation' , err ) ;
57+ }
58+ } ) ;
59+ } ) ;
60+
5061 return fastifyOtelInstrumentationInstance ;
5162} ) ;
5263
@@ -136,16 +147,6 @@ export function setupFastifyErrorHandler(fastify: FastifyInstance): void {
136147 } ) ;
137148 }
138149
139- if ( fastifyOtelInstrumentationInstance ) {
140- // Setting after callback to prevent this plugin from throwing version mismatch errors
141- fastify . register ( fastifyOtelInstrumentationInstance . plugin ( ) ) . after ( err => {
142- if ( err ) {
143- // eslint-disable-next-line no-console
144- DEBUG_BUILD && logger . warn ( 'Failed to register Fastify Otel instrumentation plugin' , err ) ;
145- }
146- } ) ;
147- }
148- // eslint-disable-next-line @typescript-eslint/no-floating-promises
149150 fastify . register ( plugin ) ;
150151}
151152
0 commit comments