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

为.NET 7成熟应用完善Application Insights配置的关键步骤咨询

.NET7 旧应用 Application Insights 深度配置方案

一、捕获所有异常(含try/catch块内的异常)

默认情况下,Application Insights仅收集未冒泡到顶层的未处理异常。要覆盖所有异常场景,推荐两种低侵入的通用实现:

1. 全局异常拦截+统一日志规范

  • 注册全局异常过滤器(适用于MVC/Web API):
    如果用Startup.cs,在ConfigureServices中添加:
    services.AddControllers(options =>
    {
        options.Filters.Add<GlobalExceptionFilter>();
    });
    
    实现过滤器类:
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<GlobalExceptionFilter> _logger;
    
        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }
    
        public void OnException(ExceptionContext context)
        {
            _logger.LogError(context.Exception, "未处理异常:请求路径 {Path}", context.HttpContext.Request.Path);
            context.ExceptionHandled = true; // 按需标记为已处理
        }
    }
    
  • 统一catch块日志:要求所有业务代码的catch块通过ILogger.LogError(ex, "异常描述")记录异常,Application Insights会自动抓取这些日志中的异常信息,无需额外配置。

2. 增强Application Insights异常收集

确保配置中启用完整的异常跟踪:

// Startup.cs 或 Program.cs
services.AddApplicationInsightsTelemetry(options =>
{
    options.EnableAdaptiveSampling = true; // 自动调整采样率,避免数据过载
    options.InstrumentationKey = "你的实例InstrumentationKey";
});

二、拆分控制器处理耗时与数据库响应耗时

无需手动为每个控制器加日志,借助Application Insights原生依赖跟踪即可实现:

1. 启用默认依赖跟踪

AddApplicationInsightsTelemetry会自动注册SQL Server、EF Core的依赖跟踪模块,无需额外代码。配置完成后,在Application Insights的依赖项面板中,可直接查看每个数据库调用的耗时、执行状态;在请求面板中能看到控制器整体处理耗时,两者对比即可清晰拆分。

2. 补充EF Core SQL日志(可选)

如果需要查看具体SQL语句,在DbContext中启用日志:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.LogTo(message => _logger.LogInformation(message), LogLevel.Information)
                  .EnableSensitiveDataLogging(false); // 生产环境禁用敏感数据日志
}

这些日志会自动关联到对应请求,便于排查慢SQL问题。

3. 自定义操作耗时跟踪(特殊场景)

针对非数据库的自定义业务逻辑,可封装通用的操作跟踪方法:

public static async Task TrackOperationAsync(this ILogger logger, string operationName, Func<Task> operation)
{
    using var operationHolder = new OperationHolder<RequestTelemetry>(
        TelemetryConfiguration.Active, operationName);
    
    try
    {
        await operation();
        operationHolder.Telemetry.Success = true;
    }
    catch (Exception ex)
    {
        logger.LogError(ex, "操作 {OperationName} 失败", operationName);
        operationHolder.Telemetry.Success = false;
        throw;
    }
}

业务代码中调用await _logger.TrackOperationAsync("导出数据", async () => { /* 业务逻辑 */ }),即可在Application Insights中看到该操作的独立耗时统计。

总结:手动操作量

  • 异常捕获:仅需添加全局异常过滤器,确保业务代码遵循ILogger记录异常的规范(已有统一日志的项目几乎无需修改业务代码)。
  • 耗时拆分:零业务代码修改,仅需确认Application Insights依赖跟踪配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 11:02:40