ABP vNext + Azure Application Insights:APM 监控与性能诊断最佳实践

发布于:2025-06-25 ⋅ 阅读:(21) ⋅ 点赞:(0)

ABP vNext + Azure Application Insights:APM 监控与性能诊断最佳实践 🚀



1️⃣ 集成目标与环境要求

项目 最低版本
.NET SDK 6.0
ABP vNext 7.0
Application Insights Azure 实例 / Emulator
环境变量注入 APPLICATIONINSIGHTS_CONNECTION_STRING

💡 本地调试


2️⃣ 安装 SDK 与注入服务

dotnet add package Microsoft.ApplicationInsights.AspNetCore
// Program.cs
builder.Services.AddApplicationInsightsTelemetry(options =>
{
    options.ConnectionString = builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
});
builder.Services.AddSingleton<TelemetryClient>();
builder.Logging.AddApplicationInsights();

3️⃣ 日志与链路追踪整合

🔥 系统流水线示意图

ABP 应用
ILogger
ActivitySource
ApplicationService / Controller
BackgroundWorker
TelemetryPipeline
Application Insights SDK
Azure Monitor / Log Analytics
Dashboard / Alert Rules

✅ ILogger 原生接入

public class OrderAppService : ApplicationService
{
    private readonly ILogger<OrderAppService> _logger;
    public OrderAppService(ILogger<OrderAppService> logger) => _logger = logger;
    public Task<string> PlaceOrder()
    {
        _logger.LogInformation("🛒 开始执行下单逻辑");
        return Task.FromResult("OK");
    }
}

✅ 手动埋点(TelemetryClient)

public class OrderManager
{
    private readonly TelemetryClient _telemetry;
    public OrderManager(TelemetryClient telemetry) => _telemetry = telemetry;

    public void TrackLatency(long ms)
    {
        _telemetry.TrackMetric("OrderService.QueryOrder.LatencyMs", ms);
    }
}

4️⃣ 多租户与用户上下文注入

public class AbpTelemetryInitializer : ITelemetryInitializer
{
    private readonly ICurrentUser _currentUser;
    public AbpTelemetryInitializer(ICurrentUser currentUser) => _currentUser = currentUser;

    public void Initialize(ITelemetry telemetry)
    {
        if (_currentUser.IsAuthenticated)
        {
            telemetry.Context.User.Id = _currentUser.Id?.ToString();
            telemetry.Context.Properties["TenantId"] = _currentUser.TenantId?.ToString();
        }
    }
}

// 注册
builder.Services.AddSingleton<ITelemetryInitializer, AbpTelemetryInitializer>();

5️⃣ 后台任务中的链路恢复

using System.Diagnostics;

private static readonly ActivitySource BackgroundSource = new("AbpApp.BackgroundJobs");
public async Task ExecuteJobAsync()
{
    using var activity = BackgroundSource.StartActivity("SyncOrderTask");
    _telemetry.TrackTrace("🔄 执行后台同步订单", SeverityLevel.Information);
    // …业务逻辑…
}

⚠️ 推荐使用 ActivitySource 以兼容 OpenTelemetry。


6️⃣ 采样与 TelemetryChannel 调优

🎯 采样 (Sampling)

builder.Services.Configure<TelemetryConfiguration>(config =>
{
    config.DefaultTelemetrySink
          .TelemetryProcessorChainBuilder
          .UseSampling(percentage: 10)  // 10% 采样
          .Build();
});

⚙ TelemetryChannel 调优

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.WindowsServer.Channel;

var channel = new ServerTelemetryChannel
{
    MaxTelemetryBufferCapacity = 500,
    FlushInterval = TimeSpan.FromSeconds(5)
};
builder.Services.AddSingleton<ITelemetryChannel>(channel);

7️⃣ 自定义指标与告警自动化

// 上报慢 SQL 延迟
_telemetry.TrackMetric("Sql.Query.LatencyMs", elapsedMilliseconds);
// Azure Monitor 告警查询示例
customMetrics
| where name == "Sql.Query.LatencyMs"
| summarize avg(value) by bin(timestamp, 5m)
| where avg_value > 300

8️⃣ CLI 示例:创建告警

az monitor metrics alert create   --name "HighSqlLatency"   --resource-group MyRG   --scopes /subscriptions/<sub>/resourceGroups/MyRG/providers/Microsoft.Insights/components/MyAI   --condition "avg CustomMetrics.Sql.Query.LatencyMs > 300"   --action /subscriptions/<sub>/resourceGroups/MyRG/providers/Microsoft.Web/sites/MyFunc/functions/RestartService

9️⃣ 多环境与安全配置

  • 禁止appsettings.json 明文保存连接串
  • ✅ 使用 环境变量Azure Key Vault
  • 📁 在 appsettings.{Development|Production}.json 中管理差异
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  }
}

🔟 Azure Key Vault 集成示例

using Azure.Identity;

builder.Configuration
       .AddAzureKeyVault(
           new Uri("https://<YourKeyVault>.vault.azure.net/"),
           new DefaultAzureCredential());

1️⃣1️⃣ OpenTelemetry 混合方案

builder.Services.AddOpenTelemetryTracing(b =>
{
    b.AddAspNetCoreInstrumentation()
     .AddHttpClientInstrumentation()
     .AddSource("AbpApp.BackgroundJobs")
     .AddAzureMonitorTraceExporter(o =>
     {
         o.ConnectionString = builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
     });
});
OTEL + AI
Trace
OpenTelemetry SDK
ASP.NET Core
Azure Monitor Trace Exporter
Azure Monitor

1️⃣2️⃣ 拓展建议

  • 🛠 自愈脚本:结合 Logic App、Function 或 Runbook
  • 📊 混合监控:Prometheus + Grafana + AI 混合可视化
  • 📈 性能对比:集成前后 QPS/延迟/成本评估
  • 🚀 CI/CD 集成:环境变量 & Key Vault 策略自动注入

✅ 参考文档

📘 Application Insights 文档
📘 ABP 日志扩展指南


网站公告

今日签到

点亮在社区的每一天
去签到