如何在.NET Core 2.1的应用程序洞察中从采样中排除异常和错误记录? [英] How to exclude Exception and Error logging from sampling in Application Insights in .NET Core 2.1?

查看:48
本文介绍了如何在.NET Core 2.1的应用程序洞察中从采样中排除异常和错误记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行具有以下规范的Web API:

  • ASP.NET Core 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存储桶。因此,我找到了应用程序洞察的以下配置:

        var builder = aiTelemetryConfiguration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;
        builder.UseAdaptiveSampling(excludedTypes: "Trace;Exception");
        builder.Build();
在这里,我从自适应采样中排除了跟踪和异常。

此配置目前正在生产中。它每分钟处理+/-50K个请求。但异常存储桶保持为空。

我注意到踪迹之间的这些信息:

AI(内部):[Microsoft-ApplicationInsights-Core][msg=日志错误];[msg=初始化Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers.AspNetCoreEnvironmentTelemetryInitializer,异常消息时异常-系统。ArgumentException:字典中已存在该键。 在System.Collections.Concurrent.ConcurrentDictionary`2.System.Collections.Generic.IDictionary.Add(TKey密钥上,TValue值) 在Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers.AspNetCoreEnvironmentTelemetryInitializer.Initialize(ITelemetry遥测) 在Microsoft.ApplicationInsights.TelemetryClient.Initialize(ITelemetry遥测)]

AI:公制提取程序检测到SsamingPercentage<;为100的遥测项目。应在采样处理器或任何其他可能过滤出遥测项目的遥测处理器之前使用指标提取程序。否则,提取的指标可能不正确。

明确地说,我正在查看以下位置:

  • Azure应用程序洞察->搜索->跟踪|自定义事件|异常
  • 使用此查询记录分析:

     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>();

来自official documentation about sampling。并且我从启动中删除了添加的配置。

我会随时向您报告改进情况。

这篇关于如何在.NET Core 2.1的应用程序洞察中从采样中排除异常和错误记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆