@@ -215,6 +215,9 @@ export class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumen
215
215
attributes : Object . assign ( attributes , metadata . attributes ) ,
216
216
} ) ;
217
217
218
+ const parentContext = context . active ( ) ;
219
+ let currentContext = trace . setSpan ( parentContext , span ) ;
220
+
218
221
const { requestHook } = instrumentation . getConfig ( ) ;
219
222
if ( requestHook ) {
220
223
safeExecuteInTheMiddle (
@@ -234,12 +237,15 @@ export class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumen
234
237
}
235
238
236
239
let spanHasEnded = false ;
240
+ // TODO: Fix router spans (getRouterPath does not work properly) to
241
+ // have useful names before removing this branch
237
242
if (
238
- metadata . attributes [ AttributeNames . EXPRESS_TYPE ] ! ==
239
- ExpressLayerType . MIDDLEWARE
243
+ metadata . attributes [ AttributeNames . EXPRESS_TYPE ] = ==
244
+ ExpressLayerType . ROUTER
240
245
) {
241
246
span . end ( ) ;
242
247
spanHasEnded = true ;
248
+ currentContext = parentContext ;
243
249
}
244
250
// listener for response.on('finish')
245
251
const onResponseFinish = ( ) => {
@@ -278,12 +284,12 @@ export class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumen
278
284
( req [ _LAYERS_STORE_PROPERTY ] as string [ ] ) . pop ( ) ;
279
285
}
280
286
const callback = args [ callbackIdx ] as Function ;
281
- return callback . apply ( this , arguments ) ;
287
+ return context . bind ( parentContext , callback ) . apply ( this , arguments ) ;
282
288
} ;
283
289
}
284
290
285
291
try {
286
- return original . apply ( this , arguments ) ;
292
+ return context . bind ( currentContext , original ) . apply ( this , arguments ) ;
287
293
} catch ( anyError ) {
288
294
const [ error , message ] = asErrorAndMessage ( anyError ) ;
289
295
span . recordException ( error ) ;
@@ -296,7 +302,7 @@ export class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumen
296
302
/**
297
303
* At this point if the callback wasn't called, that means either the
298
304
* layer is asynchronous (so it will call the callback later on) or that
299
- * the layer directly end the http response, so we'll hook into the "finish"
305
+ * the layer directly ends the http response, so we'll hook into the "finish"
300
306
* event to handle the later case.
301
307
*/
302
308
if ( ! spanHasEnded ) {
0 commit comments