You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8 Web API中Application Insights无法记录自定义异常日志

.NET 8 Web API在Azure App Service上的Application Insights异常日志不记录问题解决

问题背景

部署在Azure App Service的.NET 8 Web API遇到以下日志问题:

  • 数据库逻辑出错返回500响应时,Azure Application Insights中无对应异常日志
  • 使用LogError/LogInformation方法并传入异常对象作为第一个参数时,日志无法被记录;仅传入文本消息则正常记录
  • 重新抛出自定义ConcurrencyException时,AI不记录该异常;但抛出全新Exception时可正常捕获
  • 使用Microsoft.ApplicationInsights.AspNetCore 2.22.0版本,已在Startup中调用services.AddApplicationInsightsTelemetry(),配置如下:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
}

解决方案

1. 更新Application Insights包版本

2.22.0版本存在自定义异常日志处理的已知问题,建议更新至最新稳定版本:

dotnet add package Microsoft.ApplicationInsights.AspNetCore --version <最新稳定版本号>

2. 调整Application Insights配置

修改appsettings.json,确保异常追踪启用并临时关闭采样(排查阶段避免日志被过滤):

{
  "ApplicationInsights": {
    "InstrumentationKey": "你的仪表板密钥",
    "EnableAdaptiveSampling": false,
    "ExceptionTracking": {
      "Enabled": true,
      "TrackExceptionsAsExceptionTelemetry": true
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.Hosting.Lifetime": "Information",
      "你的控制器命名空间": "Debug"
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
}

3. 手动追踪异常(快速验证)

在控制器中注入TelemetryClient,在catch块中手动调用TrackException方法强制上报异常:

using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Logging;

public class YourController : ControllerBase
{
    private readonly ILogger<YourController> _logger;
    private readonly TelemetryClient _telemetryClient;

    public YourController(ILogger<YourController> logger, TelemetryClient telemetryClient)
    {
        _logger = logger;
        _telemetryClient = telemetryClient;
    }

    [HttpPost]
    public async Task<IActionResult> UpdateCase()
    {
        try
        {
            var updatedCase = await ...; // 数据库更新逻辑
            return Ok(...);
        }
        catch (ConcurrencyException cEx)
        {
            _logger.LogError(cEx, "捕获到并发冲突异常");
            _telemetryClient.TrackException(cEx); // 手动向AI上报异常
            throw;
        }
    }
}

4. 配置全局异常过滤器

创建全局过滤器,确保所有未处理异常被自动捕获并上报:

using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Mvc.Filters;

public class AiExceptionTrackingFilter : IExceptionFilter
{
    private readonly TelemetryClient _telemetryClient;

    public AiExceptionTrackingFilter(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

    public void OnException(ExceptionContext context)
    {
        // 追踪异常到Application Insights
        _telemetryClient.TrackException(context.Exception);
        // 若不需要框架默认的500响应,可设置context.ExceptionHandled = true;
    }
}

在Program.cs(或Startup.cs)中注册过滤器:

services.AddControllers(options =>
{
    options.Filters.Add<AiExceptionTrackingFilter>();
});

5. 优化自定义异常的序列化支持

为自定义异常添加序列化构造函数,确保AI能正确解析异常完整信息:

using System.Runtime.Serialization;

[Serializable]
public class ConcurrencyException : Exception
{
    public ConcurrencyException() { }

    public ConcurrencyException(string message) : base(message) { }

    public ConcurrencyException(string message, Exception inner) : base(message, inner) { }

    protected ConcurrencyException(SerializationInfo info, StreamingContext context) 
        : base(info, context) { }
}

验证步骤

  1. 将更新后的代码部署到Azure App Service
  2. 触发异常场景
  3. 等待5-10分钟(AI日志存在传输延迟)
  4. 在Azure门户的Application Insights中,查看异常面板或搜索exceptions类型日志

内容的提问来源于stack exchange,提问作者Neil Mountford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 01:29:52