首页 > 解决方案 > Application Insights 遥测处理器未捕获异常

问题描述

我有一个自定义遥测处理器,可将自定义异常字段发送到 Application Insights。

例如,如果我抛出一个像这样的自定义异常

class MyException : Exception
{
   public string AdditionalData { get; set; }
}

然后它AdditionalData作为自定义应用洞察字段发送。

public class CustomExceptionDataTelemetryProcessor : ITelemetryProcessor
{
    /// <summary>
    /// Default exception fields that should be ignore because they are part of logs by default
    /// </summary>
    private static IEnumerable<string> _DefaultExceptionFields = new Exception().GetType().GetProperties().Select(e => e.Name);
    private readonly ITelemetryProcessor _next;

    public CustomExceptionDataTelemetryProcessor(ITelemetryProcessor next)
    {
        _next = next;
    }

    public void Process(ITelemetry item)
    {
        ModifyItem(item);
        _next.Process(item);
    }

    /// <summary>
    /// Adds exception fields as custom data
    /// </summary>
    private void ModifyItem(ITelemetry item)
    {
        if (!(item is ExceptionTelemetry exceptionTelementry))
        {
            return;
        }

        var exception = exceptionTelementry.Exception;
        var exceptionType = exception.GetType();

        foreach (var property in exceptionType.GetProperties())
        {
            // ignore default fields
            if (_DefaultExceptionFields.Contains(property.Name))
            {
                continue;
            }
            
            var value = property.GetValue(exception);
            var serializedValue = (value is string) ? value.ToString() : HttpClientUtils.Serialize(value);
            exceptionTelementry.Properties[property.Name] = serializedValue;
        }
    }
}

我像这样注册这个处理器

var telemetryBuilder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
telemetryBuilder.Use((next) => new CustomExceptionDataTelemetryProcessor(next));
telemetryBuilder.Build();

2.2.1Microsoft.ApplicationInsights.AspNetCore版本一切正常。

如果我升级到最新版本2.15.0,它仍然可以正常工作,但我收到警告说注册码已被弃用,所以我根据文档对其进行了更改

services.AddApplicationInsightsTelemetryProcessor<CustomExceptionDataTelemetryProcessor>();

但是现在异常不再被处理器“捕获”。只有RequestTelemetry或类型的项目DependencyTelemetry。没有类型的项目ExceptionTelemetry

我可以用旧方式离开注册,但认为这可能表明某些事情不太正确,可能会导致其他地方出现其他问题。

我尝试在注册自己的初始化程序和处理器之前删除所有初始化程序和处理器,但这没有帮助。其他东西可能会过滤掉异常。

services.RemoveAll(typeof(ITelemetryInitializer));
services.RemoveAll(typeof(ITelemetryProcessor));

标签: c#.net-coreazure-application-insightstelemetry

解决方案


它适用于版本2.13.1Microsoft.ApplicationInsights.AspNetCore

我还Microsoft.ApplicationInsights安装了不同版本的 NuGet 包。将其删除并仅保留Microsoft.ApplicationInsights.AspNetCore.


推荐阅读