diff --git a/plugins/node/opentelemetry-instrumentation-redis/src/utils.ts b/plugins/node/opentelemetry-instrumentation-redis/src/utils.ts index 9ad22b2b43..52729c3df5 100644 --- a/plugins/node/opentelemetry-instrumentation-redis/src/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-redis/src/utils.ts @@ -127,6 +127,7 @@ export const getTracedInternalSendCommand = ( const originalCallback = arguments[0].callback; if (originalCallback) { + const originalContext = context.active(); (arguments[0] as RedisCommand).callback = function callback( this: unknown, err: Error | null, @@ -146,7 +147,12 @@ export const getTracedInternalSendCommand = ( } endSpan(span, err); - return originalCallback.apply(this, arguments); + return context.with( + originalContext, + originalCallback, + this, + ...arguments + ); }; } try { diff --git a/plugins/node/opentelemetry-instrumentation-redis/test/redis.test.ts b/plugins/node/opentelemetry-instrumentation-redis/test/redis.test.ts index 18b6be3107..8805317191 100644 --- a/plugins/node/opentelemetry-instrumentation-redis/test/redis.test.ts +++ b/plugins/node/opentelemetry-instrumentation-redis/test/redis.test.ts @@ -212,6 +212,16 @@ describe('redis@2.x', () => { }); }); }); + + it('should invoke callback with original command context', () => { + const rootSpan = tracer.startSpan('test span'); + context.with(trace.setSpan(context.active(), rootSpan), () => { + client.set('callbacksTestKey', 'value', () => { + const activeSpan = trace.getSpan(context.active()); + assert.strictEqual(activeSpan, rootSpan); + }); + }); + }); }); describe('Removing instrumentation', () => {