opentelemetry-js icon indicating copy to clipboard operation
opentelemetry-js copied to clipboard

Enabling ESM and CommonJS Support in OpenTelemetry Instrumentation Libraries

Open swapnil-nagar opened this issue 5 months ago • 0 comments
trafficstars

We added the support for the opentelemetry instrumentation for azure functions, we created a new package to support the azure-functions-nodejs-opentelemetry, and we want to make sure our instrumentation supports both CommonJS (CJS) and ESM environments.

Issue

Currently, OpenTelemetry instrumentations use InstrumentationNodeModuleDefinition. This works great for CommonJS, but it does works with ESM.

This makes it very difficult for OpenTelemetry instrumentation libraries to support ESM unless we expose some manual patching API — which users must call after importing.

Reference: https://github.com/Azure/azure-functions-nodejs-opentelemetry/blob/main/src/instrumentation.ts

export class AzureFunctionsInstrumentation extends InstrumentationBase {
  protected init(): InstrumentationNodeModuleDefinition {
    // Only return definitions in CJS
      return new InstrumentationNodeModuleDefinition(
          '@azure/functions',
          ['^4.5.0'],
          (exports) => this._patch(exports),
          (exports) => this._unpatch(exports),
        );
  }

  public patch(azFunc: typeof import('@azure/functions')) {
    // Propogate OtelContext at functions pre invocation 
    // azFunc.app.hook.preInvocation(...)
  }
}

ESM users must do this manually (This is the only solution which seems to work for our customers)


import { AzureFunctionsInstrumentation } from '@my/instrumentation';
import * as azureFunctions from '@azure/functions';

const instr = new AzureFunctionsInstrumentation();
instr.patch(azureFunctions); // Manual patch

NOTE: We followed the link esm-support and tried with experimental loader in NODE_OPTIONS, but proposed solution did not work.

Question

Is there a better solution to unblock our customers other than invoking a manually patching?

swapnil-nagar avatar Jun 09 '25 21:06 swapnil-nagar