簡體   English   中英

如何從 .NET Core 2.1 中 Application Insights 的采樣中排除異常和錯誤日志記錄?

[英]How to exclude Exception and Error logging from sampling in Application Insights in .NET Core 2.1?

我正在運行具有以下規格的 Web api:

  • ASP.NET 核心 2.1
  • Microsoft.ApplicationInsights.AspNetCore 2.13.1
  • 托管在 Azure 應用服務中。

Startup.cs ConfigureServices 中,我添加了:

services.AddApplicationInsightsTelemetry();

_loggerFactory.AddAzureWebAppDiagnostics();

我在 Startup.cs 中設置了自定義異常處理程序:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseCustomExceptionHandler(telemetryClient, _loggerFactory);
}

在這個 CustomExceptionHandler 中,我嘗試記錄異常,如:

var logger = loggerFactory.CreateLogger("Unhandled Exception");
logger.LogError(ex, errorId);

var telemetryProperties = new Dictionary<string, string>();
telemetryProperties.Add("errorId", errorId);
telemetryProperties.Add("traceIdentifier", context.TraceIdentifier);

telemetryClient.TrackException(ex, properties: telemetryProperties);

有了此配置,並非所有異常或錯誤日志都到達 Log Analytics 存儲桶。 所以我找到了 Application Insights 的這個配置:

        var builder = aiTelemetryConfiguration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;
        builder.UseAdaptiveSampling(excludedTypes: "Trace;Exception");
        builder.Build();

在這里,我從自適應采樣中排除了 Trace 和 Exception。

目前此配置正在生產中。 它每分鍾處理 +/- 50k 請求。 但異常桶保持空。

我注意到跟蹤之間的這些消息:

AI(內部):[Microsoft-ApplicationInsights-Core] [msg=Log Error];[msg=Exception while initializing Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers.AspNetCoreEnvironmentTelemetryInitializer,異常消息 - System.ArgumentException:該鍵已存在於字典中。 在 System.Collections.Concurrent.ConcurrentDictionary`2.System.Collections.Generic.IDictionary.Add(TKey 鍵,TValue 值) 在 Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers.AspNetCoreEnvironmentTelemetryInitializer.Initialize(ITelemetry 遙測) 在 Microsoft.ApplicationInsights.TelemetryApplicationInsights.Telemetry初始化(ITelemetry遙測)]

AI:指標提取器檢測到 SamplingPercentage < 100 的遙測項目。應在采樣處理器或任何其他可能過濾遙測項目的遙測處理器之前使用指標提取器。 否則,提取的指標可能不正確。

需要明確的是,我正在查看這些位置:

  • Azure Application Insights -> 搜索 -> 跟蹤|自定義事件|異常
  • 使用此查詢進行日志分析:

     exceptions | order by timestamp desc

這至少是禁用采樣的正確方法嗎?

提前謝謝了。

我現在添加這個 TelemetryInitializer:

public class ExceptionTelemetrySamplingFilter : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        if (telemetry is ExceptionTelemetry)
        {
            ((ISupportSampling)telemetry).SamplingPercentage = 100;
        }
    }
}

並注冊它:

services.AddSingleton<ITelemetryInitializer, ExceptionTelemetrySamplingFilter>();

它來自關於采樣官方文檔 我從啟動中刪除了添加的配置。

我會及時通知您改進情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM