Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"types": "./dist/commonjs/index.d.ts",
"type": "module",
"scripts": {
"build": "npm run clean && tsc -p tsconfig.src.json && tsc -p tsconfig.src.cjs.json",
"build": "npm run clean && tsc -p tsconfig.src.json && tsc -p tsconfig.src.cjs.json && npm run fixup-cjs",
"fixup-cjs": "node scripts/fixup-cjs.cjs",
"clean": "rimraf dist",
"lint": "eslint src test",
"lint:fix": "eslint src test --fix",
Expand Down
59 changes: 59 additions & 0 deletions scripts/fixup-cjs.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Post-build fixups for the CommonJS output.
//
// The ESM build (dist/esm/) works as-is. The CJS build (dist/commonjs/)
// needs two fixups:
//
// 1. A package.json with {"type":"commonjs"} so Node doesn't treat .js
// files as ESM (the root package.json has "type":"module").
//
// 2. The module-cjs.cts polyfill must replace module.ts in the CJS output,
// because module.ts uses import.meta.url which is ESM-only.
//
// 3. The Azure Functions instrumentation import must be fixed. The ESM
// build uses a default import (required because the package is a webpack
// bundle and Node ESM can't extract named exports). In CJS, the
// __importDefault helper double-wraps the require result, so we replace
// it with a direct require + destructure.

const fs = require("fs");
const path = require("path");

const cjsDir = path.join(__dirname, "..", "dist", "commonjs");

// 1. CJS package.json marker
fs.writeFileSync(path.join(cjsDir, "package.json"), '{"type":"commonjs"}\n');

// 2. module.ts → module-cjs.cts polyfill swap
const sharedDir = path.join(cjsDir, "shared");
fs.copyFileSync(
path.join(sharedDir, "module-cjs.cjs"),
path.join(sharedDir, "module.js"),
);
// Keep source maps consistent: copy the CJS map or remove the stale ESM one
const moduleCjsMapPath = path.join(sharedDir, "module-cjs.cjs.map");
const moduleJsMapPath = path.join(sharedDir, "module.js.map");
if (fs.existsSync(moduleCjsMapPath)) {
fs.copyFileSync(moduleCjsMapPath, moduleJsMapPath);
} else if (fs.existsSync(moduleJsMapPath)) {
fs.unlinkSync(moduleJsMapPath);
}

Comment thread
hectorhdzg marked this conversation as resolved.
// 3. Fix Azure Functions default-import in CJS output
const handlerPath = path.join(cjsDir, "azureMonitor", "traces", "handler.js");
const handler = fs.readFileSync(handlerPath, "utf8");
const azureFunctionsImportPattern =
/const functions_opentelemetry_instrumentation_1 = __importDefault\(require\("@azure\/functions-opentelemetry-instrumentation"\)\);\s*const \{ AzureFunctionsInstrumentation \} = functions_opentelemetry_instrumentation_1\.default;/;
// Replace the __importDefault pattern with a direct require
const updatedHandler = handler.replace(
azureFunctionsImportPattern,
'const { AzureFunctionsInstrumentation } = require("@azure/functions-opentelemetry-instrumentation");',
);
if (updatedHandler === handler) {
throw new Error(
`Azure Functions CJS import fixup did not match expected output in ${handlerPath}. ` +
`The emitted CommonJS handler format may have changed; update scripts/fixup-cjs.cjs before publishing.`,
);
}
fs.writeFileSync(handlerPath, updatedHandler);

console.log("CJS fixups applied.");
6 changes: 5 additions & 1 deletion src/azureMonitor/traces/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ import type { InternalConfig } from "../../shared/config.js";
import type { MetricHandler } from "../metrics/handler.js";
import { ignoreOutgoingRequestHook } from "../utils/common.js";
import { AzureMonitorSpanProcessor } from "./spanProcessor.js";
import { AzureFunctionsInstrumentation } from "@azure/functions-opentelemetry-instrumentation";
// Default-import + destructure: this package is a webpack bundle so Node.js
// ESM cannot extract named exports from it (see Node error SyntaxError:
// "Named export 'AzureFunctionsInstrumentation' not found").
import azureFunctionsOtelPkg from "@azure/functions-opentelemetry-instrumentation";
const { AzureFunctionsInstrumentation } = azureFunctionsOtelPkg;
import type { Instrumentation } from "@opentelemetry/instrumentation";
import { ApplicationInsightsSampler } from "./sampler.js";

Expand Down
48 changes: 30 additions & 18 deletions src/distro/distro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { NodeSDK } from "@opentelemetry/sdk-node";
import type { MetricReader, ViewOptions } from "@opentelemetry/sdk-metrics";
import { type SpanProcessor, BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import type { LogRecordProcessor } from "@opentelemetry/sdk-logs";
import type { Instrumentation } from "@opentelemetry/instrumentation";

import { InternalConfig } from "../shared/config.js";
import { MetricHandler } from "../azureMonitor/metrics/index.js";
Expand Down Expand Up @@ -38,7 +39,7 @@ let disposeAzureMonitor: (() => void) | undefined;
*
* This is the primary entry point for the distro. It sets up OpenTelemetry
* providers and instrumentations, then attaches the configured exporters:
* - Azure Monitor (when `options.azureMonitor` is provided)
* - Azure Monitor (enabled by default; disable with `options.azureMonitor.enabled = false`)
* - OTLP HTTP (when `OTEL_EXPORTER_OTLP_ENDPOINT` is set)
* - A365 (when `options.a365.enabled` is true or `ENABLE_A365_OBSERVABILITY_EXPORTER=true`)
*
Expand All @@ -48,8 +49,13 @@ export function useMicrosoftOpenTelemetry(options?: MicrosoftOpenTelemetryOption
const config = new InternalConfig(options);
patchOpenTelemetryInstrumentationEnable();

const azureMonitorEnabled = options?.azureMonitor?.enabled !== false;

// ── Azure Monitor components (statsbeat, browser SDK loader, etc.) ─
disposeAzureMonitor = setupAzureMonitorComponents(config);
disposeAzureMonitor = undefined;
if (azureMonitorEnabled) {
disposeAzureMonitor = setupAzureMonitorComponents(config);
}
Comment thread
hectorhdzg marked this conversation as resolved.

// ── Register global providers ─────────────────────────────────────
// Remove global providers in OpenTelemetry, these would be overridden if present
Expand All @@ -67,14 +73,21 @@ export function useMicrosoftOpenTelemetry(options?: MicrosoftOpenTelemetryOption
const globalOpentelemetryApiKey = Symbol.for("opentelemetry.js.api.1");
delete (globalThis as Record<symbol, unknown>)[globalOpentelemetryApiKey];

// ── Azure Monitor handlers ────────────────────────────────────────
const metricHandler = new MetricHandler(config);
const traceHandler = new TraceHandler(config, metricHandler);
const logHandler = new LogHandler(config, metricHandler);

const instrumentations = traceHandler
.getInstrumentations()
.concat(logHandler.getInstrumentations());
// ── Azure Monitor handlers (conditional) ──────────────────────────
let metricHandler: MetricHandler | undefined;
let traceHandler: TraceHandler | undefined;
let logHandler: LogHandler | undefined;
const instrumentations: Instrumentation[] = [];

if (azureMonitorEnabled) {
metricHandler = new MetricHandler(config);
traceHandler = new TraceHandler(config, metricHandler);
logHandler = new LogHandler(config, metricHandler);
instrumentations.push(
...traceHandler.getInstrumentations(),
...logHandler.getInstrumentations(),
);
}
Comment thread
hectorhdzg marked this conversation as resolved.

const resourceDetectorsList = parseResourceDetectorsFromEnvVar();

Expand All @@ -84,9 +97,8 @@ export function useMicrosoftOpenTelemetry(options?: MicrosoftOpenTelemetryOption
const logRecordProcessors: LogRecordProcessor[] = [...(options?.logRecordProcessors || [])];
const customViews: ViewOptions[] = [...(options?.views || [])];

// Always include Azure Monitor metric reader
const metricReaders: MetricReader[] = [
metricHandler.getMetricReader(),
...(metricHandler ? [metricHandler.getMetricReader()] : []),
...(options?.metricReaders || []),
];

Expand Down Expand Up @@ -124,7 +136,7 @@ export function useMicrosoftOpenTelemetry(options?: MicrosoftOpenTelemetryOption
spanProcessors.push(a365ExportProcessor);
}

const views: ViewOptions[] = metricHandler.getViews().concat(customViews);
const views: ViewOptions[] = [...(metricHandler ? metricHandler.getViews() : []), ...customViews];

// ── Create and start NodeSDK ──────────────────────────────────────
const sdkConfig: Partial<NodeSDKConfiguration> = {
Expand All @@ -133,16 +145,16 @@ export function useMicrosoftOpenTelemetry(options?: MicrosoftOpenTelemetryOption
views,
instrumentations: instrumentations,
logRecordProcessors: [
logHandler.getAzureLogRecordProcessor(),
...(logHandler ? [logHandler.getAzureLogRecordProcessor()] : []),
...logRecordProcessors,
logHandler.getBatchLogRecordProcessor(),
...(logHandler ? [logHandler.getBatchLogRecordProcessor()] : []),
],
resource: config.resource,
sampler: traceHandler.getSampler(),
sampler: traceHandler?.getSampler(),
spanProcessors: [
traceHandler.getAzureMonitorSpanProcessor(),
...(traceHandler ? [traceHandler.getAzureMonitorSpanProcessor()] : []),
...spanProcessors,
traceHandler.getBatchSpanProcessor(),
...(traceHandler ? [traceHandler.getBatchSpanProcessor()] : []),
],
resourceDetectors: resourceDetectorsList,
};
Expand Down
7 changes: 7 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ export {
OpenTelemetryConstants,
MessageRole,
FinishReason,
Modality,
InvocationRole,
InferenceOperationType,
A365_MESSAGE_SCHEMA_VERSION,
isParentSpanRef,
createContextWithParentSpanRef,
runWithParentSpanRef,
Expand Down Expand Up @@ -72,6 +75,10 @@ export type {
OutputMessagesParam,
ResponseMessagesParam,
MessagePart,
TextPart,
ToolCallRequestPart,
ToolCallResponsePart,
ReasoningPart,
HeadersCarrier,
} from "./a365/index.js";
export type { PerRequestSpanProcessorOptions } from "./a365/index.js";
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ export interface MicrosoftOpenTelemetryOptions {
* distro level in {@link MicrosoftOpenTelemetryOptions}.
*/
export interface AzureMonitorOpenTelemetryOptions {
/** Enable or disable Azure Monitor export (Default true) */
enabled?: boolean;
/** Azure Monitor Exporter Configuration */
azureMonitorExporterOptions?: AzureMonitorExporterOptions;
/** Enable Live Metrics feature (Default false) */
Expand Down
44 changes: 44 additions & 0 deletions test/internal/unit/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -811,4 +811,48 @@ describe("Main functions", () => {

void shutdownAzureMonitor();
});

it("useMicrosoftOpenTelemetry with azureMonitor.enabled=false should skip Azure Monitor handlers", async () => {
const { useMicrosoftOpenTelemetry, shutdownMicrosoftOpenTelemetry } =
await import("../../../src/index.js");
const processor: SpanProcessor = {
forceFlush: () => Promise.resolve(),
onStart: () => {
/* no-op */
},
onEnd: () => {
/* no-op */
},
shutdown: () => Promise.resolve(),
};

useMicrosoftOpenTelemetry({
azureMonitor: { enabled: false },
spanProcessors: [processor],
});

// Providers should still be registered (the SDK still starts)
const internalSdk = _getSdkInstance();
assert.isDefined(internalSdk);

// The tracer provider should contain the user-provided processor
// but NOT Azure Monitor span processors (AzureMonitorSpanProcessor / BatchSpanProcessor)
const tracerProvider = (internalSdk as any)["_tracerProvider"];
const registeredProcessors = tracerProvider?.["_registeredSpanProcessors"] || [];
const processorNames = registeredProcessors.map((p: SpanProcessor) => p.constructor.name);
// User-provided processor (Object) should be present but no Azure Monitor ones
expect(processorNames).not.toContain("AzureMonitorSpanProcessor");
expect(processorNames).not.toContain("AzureMonitorExporterProcessor");

// Metric readers should not contain Azure Monitor readers
const meterProvider = (internalSdk as any)["_meterProvider"];
const metricReaders = meterProvider?.["_sharedState"]?.metricCollectors || [];
assert.strictEqual(
metricReaders.length,
0,
"Should have no metric readers when Azure Monitor is disabled and no custom readers provided",
);

await shutdownMicrosoftOpenTelemetry();
});
});
2 changes: 2 additions & 0 deletions test/internal/unit/traces/traceHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ describe("Library/TraceHandler", () => {
_config.instrumentationOptions = {
http: { enabled: false },
azureSdk: { enabled: false },
azureFunctions: { enabled: false },
mongoDb: { enabled: false },
mySql: { enabled: false },
postgreSql: { enabled: false },
Expand Down Expand Up @@ -258,6 +259,7 @@ describe("Library/TraceHandler", () => {
_config.instrumentationOptions = {
http: { enabled: true },
azureSdk: { enabled: false },
azureFunctions: { enabled: false },
mongoDb: { enabled: false },
mySql: { enabled: false },
postgreSql: { enabled: false },
Expand Down
Loading