@@ -9,7 +9,7 @@ const { AsyncHooksContextManager } = require('@opentelemetry/context-async-hooks
99const { BasicTracerProvider } = require ( '@opentelemetry/sdk-trace-base' ) ;
1010const constants = require ( '../constants' ) ;
1111const supportedVersion = require ( '../supportedVersion' ) ;
12- const otelApi = require ( './opentelemetryApi' ) ;
12+ const api = require ( './opentelemetryApi' ) ;
1313
1414// NOTE: Please refrain from utilizing third-party instrumentations.
1515// Instead, opt for officially released instrumentations available in the OpenTelemetry
@@ -35,7 +35,7 @@ module.exports.init = (_config, cls) => {
3535 Object . keys ( instrumentations ) . forEach ( k => {
3636 const value = instrumentations [ k ] ;
3737 const instrumentation = require ( `./${ value . name } ` ) ;
38- instrumentation . init ( { cls, api : otelApi } ) ;
38+ instrumentation . init ( { cls, api : api } ) ;
3939 value . module = instrumentation ;
4040 } ) ;
4141
@@ -93,12 +93,24 @@ module.exports.init = (_config, cls) => {
9393 }
9494 } ;
9595
96- const provider = new BasicTracerProvider ( ) ;
9796 const contextManager = new AsyncHooksContextManager ( ) ;
9897
99- otelApi . trace . setGlobalTracerProvider ( provider ) ;
100- otelApi . context . setGlobalContextManager ( contextManager ) ;
98+ /**
99+ * - OpenTelemetry uses a ProxyTracerProvider as the default global provider
100+ * when no real tracer provider has been registered.
101+ * https://github.com/open-telemetry/opentelemetry-js/blob/main/api/src/trace/ProxyTracerProvider.ts#L35
102+ * - The proxy delegates to a real provider if one is set.
103+ * - We check if the current provider is still the proxy with no delegate,
104+ * which means no provider is configured yet.
105+ * - Only in that case do we create and register our own BasicTracerProvider.
106+ */
107+ const currentProvider = api . trace . getTracerProvider ( ) ;
108+ if ( currentProvider === api . trace . _proxyTracerProvider || ! api . trace . _proxyTracerProvider . _delegate ) {
109+ const provider = new BasicTracerProvider ( ) ;
110+ api . trace . setGlobalTracerProvider ( provider ) ;
111+ }
101112
113+ api . context . setGlobalContextManager ( contextManager ) ;
102114 /**
103115 * Each instrumentation depends on @opentelemetry/instrumentation.
104116 * @opentelemetry /instrumentation has a peer dependency to @opentelemetry /api.
@@ -112,8 +124,8 @@ module.exports.init = (_config, cls) => {
112124 *
113125 * This is an npm workspace issue. Nohoisting missing.
114126 */
115- const orig = otelApi . trace . setSpan ;
116- otelApi . trace . setSpan = function instanaSetSpan ( ctx , span ) {
127+ const orig = api . trace . setSpan ;
128+ api . trace . setSpan = function instanaSetSpan ( ctx , span ) {
117129 transformToInstanaSpan ( span ) ;
118130 return orig . apply ( this , arguments ) ;
119131 } ;
0 commit comments