From 60a17ee8e343f0234443faeb6ba2b39413474dae Mon Sep 17 00:00:00 2001 From: Ran Nozik Date: Wed, 27 Apr 2022 18:45:10 +0300 Subject: [PATCH] feat: warn when hooked module is already loaded (#2926) --- CHANGELOG.md | 1 + .../src/platform/node/instrumentation.ts | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index accaf406d4b..c2c6e27cc1b 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 f67476930d7..09d6a86b292 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(