如何以编程方式将相关性 headers 添加到 Application Insights Angular http 请求

How to programmatically add correlation headers to Application Insights Angular http request

我在 Angular 应用程序中使用 npm 包 @microsoft/applicationinsights-web

我的 http 服务中有自定义 headers,它覆盖了相关性 headers('Request-Id' 和 'Request-Context')。我查看了 appInsights object,但是无法找到这两个属性以将它们附加到我的自定义 headers。有谁知道如何以编程方式处理这些问题?

应用洞察配置

private appInsights = new ApplicationInsights({
    config: {
        instrumentationKey: environment.ApplicationInsightsInstrumentationKey
    }
});

this.appInsights.loadAppInsights();

http 调用

getHttpOptions() {
    return {
        headers: new HttpHeaders({
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Content-Type': 'application/json',
            Authorization: `Bearer ${this.authService.authToken}`,
        })
    };
}

getDetails(): any {
    let detailsUrl = `${this.apiBaseUrl}${Details}`;
    return this._httpClientService.post<any>(detailsUrl, this.getHttpOptions()).pipe(
        catchError((e: any) => this.handleError(e, this)));
}

Application Insights 不支持自定义关联 headers。我们建议使用 Trace-Context standard everywhere and here is how to opt into it JS SDK

我需要查看您的代码,但听起来您是在说您正在将自定义 header 传递给 http 调用,这导致调用不包含 Request-Id 和 Request-Context header 来自 AI。我可能有偏见。我发现这个问题是因为我认为这也发生在我身上。我看到的症状是:从具有特定 headers 的 angular 服务进行 http 调用(在我的例子中是授权),并且在请求中没有看到预期的 AI headers出路。

所以我深入研究了 AI Js 存储库,发现这些存储库的价值群体被埋藏得很深,但我发现默认情况下它对 GET 请求是关闭的 (config.disableFetchTracking = true)我在测试时盲目地只查看多数调用 (GET)。

打开它后,我开始在所有未被 correlationHeaderExcludedDomains 排除的请求中看到它。

在此过程中,我还尝试按照另一个答案中的建议设置 distributedTracingMode,发现包含 W3C(填充跟踪 parent)的任何值都导致值无法正确关联人工智能。具体来说,http 函数 RequestTelemetry 与 PageViewTelemetry angular 请求相关联,而不是 http 调用 DependencyTelemetry.

我确实看到了 traceparentRequest-Id header 中的值之间的差异,所以从外面看起来是 traceparent header 优先并导致函数调用上的 parent 设置错误。 现在,我将关闭该功能,并仅使用默认的 AI

从这个日期开始,我在我的 angular 中使用最新的 JS 库,在我的函数中使用 C# 库。