@azure/monitor-opentelemetry
Version:
Azure Monitor OpenTelemetry (Node.js)
50 lines • 2.26 kB
JavaScript
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { context, propagation } from "@opentelemetry/api";
import { Logger } from "../shared/logging/index.js";
import { loadAzureFunctionCore } from "../shared/module.js";
export class AzureFunctionsHook {
constructor() {
try {
this._functionsCoreModule = loadAzureFunctionCore();
this._addPreInvocationHook();
}
catch (error) {
Logger.getInstance().debug("@azure/functions-core failed to load, not running in Azure Functions");
}
}
shutdown() {
if (this._preInvocationHook) {
this._preInvocationHook.dispose();
this._preInvocationHook = undefined;
}
this._functionsCoreModule = undefined;
}
_addPreInvocationHook() {
if (!this._preInvocationHook) {
this._preInvocationHook = this._functionsCoreModule.registerHook("preInvocation",
// eslint-disable-next-line @typescript-eslint/require-await
async (preInvocationContext) => {
const sharedContext = preInvocationContext.invocationContext;
const traceContext = sharedContext.traceContext;
// Update context to use Azure Functions one
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
let extractedContext = null;
try {
if (traceContext) {
extractedContext = propagation.extract(context.active(), {
traceparent: traceContext.traceparent || traceContext.traceParent,
tracestate: traceContext.tracestate || traceContext.traceState,
});
}
const currentContext = extractedContext || context.active();
preInvocationContext.functionCallback = context.bind(currentContext, preInvocationContext.functionCallback);
}
catch (err) {
Logger.getInstance().error("Failed to propagate context in Azure Functions", err);
}
});
}
}
}
//# sourceMappingURL=azureFnHook.js.map