diff --git a/CHANGELOG.md b/CHANGELOG.md index accaf406d4..c2c6e27cc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to this project will be documented in this file. ### :rocket: (Enhancement) * feat(ConsoleSpanExporter): export span links [#2917](https://github.com/open-telemetry/opentelemetry-js/pull/2917) @trentm +* feat: warn when hooked module is already loaded [#2926](https://github.com/open-telemetry/opentelemetry-js/pull/2926) @nozik ### :bug: (Bug Fix) diff --git a/experimental/packages/opentelemetry-instrumentation/src/platform/node/instrumentation.ts b/experimental/packages/opentelemetry-instrumentation/src/platform/node/instrumentation.ts index f67476930d..09d6a86b29 100644 --- a/experimental/packages/opentelemetry-instrumentation/src/platform/node/instrumentation.ts +++ b/experimental/packages/opentelemetry-instrumentation/src/platform/node/instrumentation.ts @@ -59,6 +59,21 @@ export abstract class InstrumentationBase } } + private _warnOnPreloadedModules(): void { + this._modules.forEach((module: InstrumentationModuleDefinition) => { + const { name } = module; + try { + const resolvedModule = require.resolve(name); + if (require.cache[resolvedModule]) { + // Module is already cached, which means the instrumentation hook might not work + this._diag.warn(`Module ${name} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${name}`); + } + } catch { + // Module isn't available, we can simply skip + } + }); + } + private _extractPackageVersion(baseDir: string): string | undefined { try { // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -134,6 +149,7 @@ export abstract class InstrumentationBase return; } + this._warnOnPreloadedModules(); for (const module of this._modules) { this._hooks.push( RequireInTheMiddle(