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

Application Insights未显示Azure Web App全部5xx错误的排查咨询

问题背景

昨晚收到某Azure Web App的数百条错误投诉,在Azure门户中看到该应用出现了数千次5xx错误:
Azure Portal 24小时内5xx错误

该应用是.NET 6 Web API,已配置Application Insights SDK,但同一时间段内Application Insights仅显示44条错误,同时却有数千条成功请求。说明Application Insights已正常连接,但无法获取完整的错误日志。


现有配置与代码

appsettings.json

{  
  "AllowedHosts": "*",  
  "ApplicationInsights": {    
    "InstrumentationKey": "Instrumentation Key from Azure"  
  },  
  "Logging": {    
    "LogLevel": {      
      "Default": "Information",      
      "Microsoft": "Warning",      
      "Microsoft.Hosting.Lifetime": "Information"    
    },    
    "ApplicationInsights": {      
      "LogLevel": {        
        "Default": "Error"      
      }    
    }  
  } 
}

Program.cs

var services = builder.Services;var configuration = builder.Configuration;

services.AddApplicationInsightsTelemetry(configuration["ApplicationInsights:InstrumentationKey"]);

控制器代码

namespace MyAPI.Controllers{
    [Route("api/[controller]")]
    [Authorize]
    [ApiController]
    public class MyController : ControllerBase
    {
        private readonly ILogger _logger;
        
        public MyController(ILogger<MyController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public async Task<ActionResult> MyTask()
        {
            try
            {
                // Do things async

                return Ok()
            }
            catch (Exception e)
            {
                _logger.LogError("{error}", e.Message);
                return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
            }
        }
    }
}

排查方向与解决办法

1. 捕获未被局部try/catch覆盖的异常

当前控制器仅捕获了MyTask方法内部的异常,但大量5xx错误可能来自:

  • 全局层面的未处理异常(比如中间件抛出、认证授权失败)
  • 异步操作中未被等待的任务抛出的异常
  • 框架级错误(路由匹配失败、模型绑定错误)

添加全局异常处理中间件捕获所有未处理异常:

// Program.cs中注册中间件
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();

// 定义全局异常中间件类
public class GlobalExceptionHandlerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger;

    public GlobalExceptionHandlerMiddleware(RequestDelegate next, ILogger<GlobalExceptionHandlerMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "未处理的全局异常");
            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            await context.Response.WriteAsync("服务器内部错误");
        }
    }
}

同时在appsettings.json中启用Application Insights自动异常跟踪:

"ApplicationInsights": {
  "InstrumentationKey": "你的密钥",
  "AutoCollectExceptions": true
}

2. 检查采样配置

Application Insights默认启用自适应采样,会过滤部分日志导致显示数量远低于实际错误数:

  • 临时关闭采样验证:在appsettings.json中添加"EnableAdaptiveSampling": false,观察错误数量是否与Azure门户一致
  • 若需保留采样,可调整规则确保错误日志不被过滤:
// Program.cs中配置采样规则
services.Configure<TelemetryConfiguration>(config =>
{
    var samplingSettings = new AdaptiveSamplingTelemetryProcessorSettings
    {
        MaxTelemetryItemsPerSecond = 5,
        ExcludedTypes = "Trace;Dependency" // 不对错误类型采样
    };
    var processor = new AdaptiveSamplingTelemetryProcessor(samplingSettings, config.TelemetrySink);
    config.TelemetryProcessorChainBuilder.Use(processor);
});

3. 完善日志记录内容

当前日志仅记录异常消息,缺失堆栈信息且配置可能存在遗漏:

  • 修改日志调用,传入完整异常对象:
_logger.LogError(ex, "执行MyTask时发生错误");
  • 补充框架级错误日志捕获,在appsettings.json中添加:
"Logging": {
  "ApplicationInsights": {
    "LogLevel": {
      "Default": "Error",
      "Microsoft.AspNetCore": "Error"
    }
  }
}

4. 检查Azure Web App原生日志

部分错误可能在到达应用代码前发生(比如IIS层面错误),需启用Web App诊断日志:

  • 在Azure门户的应用服务 -> 日志中,开启详细错误日志和诊断日志
  • 通过日志流实时查看请求错误,确认错误来源

5. 验证Application Insights配置完整性

推荐直接传入配置对象而非仅密钥,确保所有配置项生效:

services.AddApplicationInsightsTelemetry(configuration);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:57:37