@@ -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' ;
1516import type { FastifyInstance } from './fastify-v3/internal-types' ;
1617import { DEBUG_BUILD } from '../../debug-build' ;
1718
@@ -104,12 +105,22 @@ export const instrumentFastifyV3 = generateInstrumentOnce(
104105 } ) ,
105106) ;
106107
107- let fastifyOtelInstrumentationInstance : FastifyOtelInstrumentation | undefined ;
108-
109108export const instrumentFastify = generateInstrumentOnce ( INTEGRATION_NAME , ( ) => {
110109 // FastifyOtelInstrumentation does not have a `requestHook`
111110 // so we can't use `addFastifySpanAttributes` here for now
112- fastifyOtelInstrumentationInstance = new FastifyOtelInstrumentation ( ) ;
111+ const fastifyOtelInstrumentationInstance = new FastifyOtelInstrumentation ( ) ;
112+ const plugin = fastifyOtelInstrumentationInstance . plugin ( ) ;
113+
114+ diagnosticsChannel . subscribe ( 'fastify.initialization' , message => {
115+ const fastifyInstance = ( message as { fastify ?: FastifyInstance } ) . fastify ;
116+
117+ fastifyInstance ?. register ( plugin ) . after ( err => {
118+ if ( err ) {
119+ DEBUG_BUILD && logger . error ( 'Failed to setup Fastify instrumentation' , err ) ;
120+ }
121+ } ) ;
122+ } ) ;
123+
113124 return fastifyOtelInstrumentationInstance ;
114125} ) ;
115126
@@ -213,16 +224,6 @@ export function setupFastifyErrorHandler(fastify: Fastify, options?: Partial<Fas
213224 } ) ;
214225 }
215226
216- if ( fastifyOtelInstrumentationInstance ) {
217- // Setting after callback to prevent this plugin from throwing version mismatch errors
218- fastify . register ( fastifyOtelInstrumentationInstance . plugin ( ) ) . after ( err => {
219- if ( err ) {
220- // eslint-disable-next-line no-console
221- DEBUG_BUILD && logger . warn ( 'Failed to register Fastify Otel instrumentation plugin' , err ) ;
222- }
223- } ) ;
224- }
225- // eslint-disable-next-line @typescript-eslint/no-floating-promises
226227 fastify . register ( plugin ) ;
227228}
228229
0 commit comments