@azure/monitor-opentelemetry
Version: 
Azure Monitor OpenTelemetry (Node.js)
54 lines • 2.46 kB
JavaScript
;
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzureFunctionsHook = void 0;
const api_1 = require("@opentelemetry/api");
const index_js_1 = require("../shared/logging/index.js");
const module_js_1 = require("../shared/module.js");
class AzureFunctionsHook {
    constructor() {
        try {
            this._functionsCoreModule = (0, module_js_1.loadAzureFunctionCore)();
            this._addPreInvocationHook();
        }
        catch (error) {
            index_js_1.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 = api_1.propagation.extract(api_1.context.active(), {
                            traceparent: traceContext.traceparent || traceContext.traceParent,
                            tracestate: traceContext.tracestate || traceContext.traceState,
                        });
                    }
                    const currentContext = extractedContext || api_1.context.active();
                    preInvocationContext.functionCallback = api_1.context.bind(currentContext, preInvocationContext.functionCallback);
                }
                catch (err) {
                    index_js_1.Logger.getInstance().error("Failed to propagate context in Azure Functions", err);
                }
            });
        }
    }
}
exports.AzureFunctionsHook = AzureFunctionsHook;
//# sourceMappingURL=azureFnHook.js.map