diff --git a/packages/opentelemetry-plugin-http/src/http.ts b/packages/opentelemetry-plugin-http/src/http.ts index 7f5e45b2583..0a152aafe17 100644 --- a/packages/opentelemetry-plugin-http/src/http.ts +++ b/packages/opentelemetry-plugin-http/src/http.ts @@ -28,6 +28,7 @@ import { BasePlugin, NoRecordingSpan, getExtractedSpanContext, + setActiveSpan, } from '@opentelemetry/core'; import { ClientRequest, @@ -422,21 +423,24 @@ export class HttpPlugin extends BasePlugin { kind: SpanKind.CLIENT, }; const span = plugin._startHttpSpan(operationName, spanOptions); + if (!optionsParsed.headers) { + optionsParsed.headers = {}; + } + propagation.inject( + optionsParsed.headers, + undefined, + setActiveSpan(context.active(), span) + ); - return plugin._tracer.withSpan(span, () => { - if (!optionsParsed.headers) optionsParsed.headers = {}; - propagation.inject(optionsParsed.headers); - - const request: ClientRequest = plugin._safeExecute( - span, - () => original.apply(this, [optionsParsed, ...args]), - true - ); + const request: ClientRequest = plugin._safeExecute( + span, + () => original.apply(this, [optionsParsed, ...args]), + true + ); - plugin._logger.debug('%s plugin outgoingRequest', plugin.moduleName); - plugin._tracer.bind(request); - return plugin._traceClientRequest(request, optionsParsed, span); - }); + plugin._logger.debug('%s plugin outgoingRequest', plugin.moduleName); + plugin._tracer.bind(request); + return plugin._traceClientRequest(request, optionsParsed, span); }; } diff --git a/packages/opentelemetry-plugin-http/test/functionals/http-enable.test.ts b/packages/opentelemetry-plugin-http/test/functionals/http-enable.test.ts index 60d34fa45ce..1b33b32c120 100644 --- a/packages/opentelemetry-plugin-http/test/functionals/http-enable.test.ts +++ b/packages/opentelemetry-plugin-http/test/functionals/http-enable.test.ts @@ -20,7 +20,10 @@ import { Span as ISpan, SpanKind, } from '@opentelemetry/api'; -import { NoopLogger } from '@opentelemetry/core'; +import { + NoopLogger, + getActiveSpan, +} from '@opentelemetry/core'; import { NodeTracerProvider } from '@opentelemetry/node'; import { InMemorySpanExporter, @@ -751,6 +754,14 @@ describe('HttpPlugin', () => { SpanKind.CLIENT ); }); + + it('should not set span as active in context for outgoing request', async () => { + assert.deepStrictEqual(getActiveSpan(context.active()), undefined); + await httpRequest.get(`${protocol}://${hostname}:${serverPort}/test`); + assert.deepStrictEqual(getActiveSpan(context.active()), undefined); + const spans = memoryExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 2); + }); }); describe('with require parent span', () => {