ABP vNext + Azure Application Insights:APM 監控與性能診斷最佳實踐 🚀
📚 目錄
- ABP vNext + Azure Application Insights:APM 監控與性能診斷最佳實踐 🚀
- 1?? 集成目標與環境要求
- 2?? 安裝 SDK 與注入服務
- 3?? 日志與鏈路追蹤整合
- 🔥 系統流水線示意圖
- ? ILogger 原生接入
- ? 手動埋點(TelemetryClient)
- 4?? 多租戶與用戶上下文注入
- 5?? 后臺任務中的鏈路恢復
- 6?? 采樣與 TelemetryChannel 調優
- 🎯 采樣 (Sampling)
- ? TelemetryChannel 調優
- 7?? 自定義指標與告警自動化
- 8?? CLI 示例:創建告警
- 9?? 多環境與安全配置
- 🔟 Azure Key Vault 集成示例
- 1??1?? OpenTelemetry 混合方案
- 1??2?? 拓展建議
- ? 參考文檔
1?? 集成目標與環境要求
項目 | 最低版本 |
---|---|
.NET SDK | 6.0 |
ABP vNext | 7.0 |
Application Insights | Azure 實例 / Emulator |
環境變量注入 | APPLICATIONINSIGHTS_CONNECTION_STRING |
💡 本地調試:
- 可用 Azure Functions Core Tools
--inspect
- 或使用 Azurite Emulator 模擬
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?? 日志與鏈路追蹤整合
🔥 系統流水線示意圖
? 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"];});
});
1??2?? 拓展建議
- 🛠 自愈腳本:結合 Logic App、Function 或 Runbook
- 📊 混合監控:Prometheus + Grafana + AI 混合可視化
- 📈 性能對比:集成前后 QPS/延遲/成本評估
- 🚀 CI/CD 集成:環境變量 & Key Vault 策略自動注入
? 參考文檔
📘 Application Insights 文檔
📘 ABP 日志擴展指南