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

Azure上.NET6 API的Application Insights依赖图谱查看问题

解决.NET6 API在Application Insights中展示方法级依赖链路的方案

1. 启用自动方法级追踪(推荐)

.NET的AppInsights SDK支持通过配置开启自动方法追踪,无需大量手动修改代码:

  • 在Program.cs中配置AppInsights时,扩展参数以启用方法追踪,并指定需要监控的业务程序集:
builder.Services.AddApplicationInsightsTelemetry(options =>
{
    options.EnableDependencyTracking = true;
    // 开启方法级追踪
    options.DependencyTrackingOptions.EnableMethodTracking = true;
    // 添加你的业务逻辑程序集名称,避免追踪系统无关方法
    options.DependencyTrackingOptions.TrackedAssemblies.Add("Your.Business.Assembly.Name");
    // 若需捕获SQL命令文本,开启此项
    options.DependencyTrackingOptions.EnableSqlCommandTextInstrumentation = true;
});

2. 手动关联日志与请求链路

如果自动追踪无法满足需求,可通过给日志绑定操作ID实现链路关联:

  • 注入IOperationHolder<RequestTelemetry>到服务类,获取当前请求的操作ID,在日志作用域中传递该ID:
private readonly ILogger<YourService> _logger;
private readonly IOperationHolder<RequestTelemetry> _operationHolder;

public YourService(ILogger<YourService> logger, IOperationHolder<RequestTelemetry> operationHolder)
{
    _logger = logger;
    _operationHolder = operationHolder;
}

public async Task DoBusinessLogic()
{
    var operationId = _operationHolder.Telemetry.Context.Operation.Id;
    // 开启包含操作ID的日志作用域
    using (_logger.BeginScope(new Dictionary<string, object> { { "OperationId", operationId } }))
    {
        _logger.LogInformation("执行对象1的方法");
        // 调用其他服务时传递操作ID,确保链路延续
        await _object2Service.DoSubLogic(operationId);
    }
}

配置完成后,在AppInsights中点击初始HTTP请求,可在「相关项」中查看同链路的所有日志。

3. 用Activity API手动构建调用链

针对复杂异步或跨服务场景,使用.NET原生Activity类手动创建追踪节点:

public async Task ProcessRequest()
{
    // 启动Activity并关联当前请求ID
    using var activity = new Activity("Object1.Method1").Start();
    activity.SetParentId(Activity.Current?.Id ?? HttpContext.TraceIdentifier);
    
    _logger.LogInformation("执行Object1.Method1");
    
    // 调用下游方法时传递当前Activity ID作为父节点ID
    await _object2Service.Method2(activity.Id);
}

// 下游服务方法
public async Task Method2(string parentActivityId)
{
    using var activity = new Activity("Object2.Method2").Start();
    activity.SetParentId(parentActivityId);
    
    _logger.LogInformation("执行Object2.Method2");
    
    // 数据库调用会被自动识别为依赖节点
    await _dbContext.TargetEntities.ToListAsync();
}

此方式下AppInsights会自动识别这些Activity为依赖节点,在依赖图谱中展示完整调用链路。

4. 验证配置与采样设置

  • 检查采样率:若启用自适应采样,可能过滤部分数据,测试阶段可在appsettings.json中设置全量采样:
{
  "ApplicationInsights": {
    "ConnectionString": "Your_Connection_String",
    "Sampling": {
      "Percentage": 100
    }
  }
}
  • 在Azure门户的AppInsights中,进入「性能」->「依赖项」查看方法级节点;或在「日志」中执行查询dependencies | where type == "Method"验证追踪数据是否生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:30:21