microsoft / ApplicationInsights-node.js

Microsoft Application Insights SDK for Node.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Corellation Context cannot be accessed during azure functions preInvocation hooks

GravlLift opened this issue · comments

I'm using this package in azure functions and I'm attempting to set a custom property in the correlation context using Azure Functions preInvocation hook. However, the way this package works is that correlation contexts are only associated with the function handler via the wrapCallback function:

private _addPreInvocationHook() {
if (!this._preInvocationHook) {
this._preInvocationHook = this._functionsCoreModule.registerHook("preInvocation", async (preInvocationContext: PreInvocationContext) => {
try {
const modelHelper = this._getFuncModelHelper();
if (modelHelper) {
const sharedContext = <sharedFuncTypes.Context>preInvocationContext.invocationContext;
// Start an AI Correlation Context using the provided Function context
let extractedContext = CorrelationContextManager.startOperation(sharedContext);
if (extractedContext) { // Will be null if CorrelationContextManager is not enabled, we should not try to propagate context in that case
extractedContext.customProperties.setProperty("InvocationId", sharedContext.invocationId);
const traceContext = sharedContext.traceContext;
if (traceContext.attributes) {
extractedContext.customProperties.setProperty("ProcessId", traceContext.attributes["ProcessId"]);
extractedContext.customProperties.setProperty("LogLevel", traceContext.attributes["LogLevel"]);
extractedContext.customProperties.setProperty("Category", traceContext.attributes["Category"]);
extractedContext.customProperties.setProperty("HostInstanceId", traceContext.attributes["HostInstanceId"]);
extractedContext.customProperties.setProperty("AzFuncLiveLogsSessionId", traceContext.attributes["#AzFuncLiveLogsSessionId"]);
}
preInvocationContext.functionCallback = CorrelationContextManager.wrapCallback(preInvocationContext.functionCallback, extractedContext);
if (modelHelper.isHttpTrigger(preInvocationContext) && this._autoGenerateIncomingRequests) {
preInvocationContext.hookData.appInsightsExtractedContext = extractedContext;
preInvocationContext.hookData.appInsightsStartTime = Date.now(); // Start trackRequest timer
}
}
}
}
catch (err) {
Logging.warn("Failed to propagate context in Azure Functions", err);
return;
}
});

So if I attempt to call getCorrelationContext or startOperation from my hook, I get a correllation context that only exists for the lifetime of my hook and is then lost.

Do you have any suggestions on how I might accomplish my objective (outside of explicitly setting custom properties at the start of all of my functions)?