您可以在容器中執行的應用程式上啟用適用於 .NET 的 Application Insights Profiler,幾乎不需要程式代碼。 若要在容器實例上啟用 .NET Profiler,您需要:
- 將參考新增至
Microsoft.ApplicationInsights.Profiler.AspNetCore
NuGet 套件。 - 更新程式代碼以啟用 .NET 的 Profiler。
- 設定「Application Insights」連接字串。
您將在本文中了解各種方法,讓您能:
- 在專案中安裝 NuGet 套件。
- 透過協調器 (例如 Kubernetes) 設定環境變數。
- 了解生產部署的安全性考慮,例如保護 Application Insights 連接字串。
必要條件
- Application Insights 資源。 記下連接字串。
- Docker Desktop,用於組建 Docker 映像。
- 已安裝 .NET 6 SDK。
進行環境設定
複製並使用下列專案範例:
git clone https://github.com/microsoft/ApplicationInsights-Profiler-AspNetCore.git
移至容器應用程式範例:
cd examples/EnableServiceProfilerForContainerAppNet6
此範例是透過呼叫下列 CLI 命令所建立的基本專案:
dotnet new mvc -n EnableServiceProfilerForContainerApp
在
Controllers/WeatherForecastController.cs
專案中有延遲來模擬瓶頸。[HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { SimulateDelay(); ... // Other existing code. } private void SimulateDelay() { // Delay for 500ms to 2s to simulate a bottleneck. Thread.Sleep((new Random()).Next(500, 2000)); }
新增 NuGet 套件來收集 .NET Profiler 追蹤:
dotnet add package Microsoft.ApplicationInsights.Profiler.AspNetCore
啟用 Application Insights 和 .NET Profiler。
在
builder.Services.AddApplicationInsightsTelemetry()
中的builder.Services.AddServiceProfiler()
方法後面新增WebApplication.CreateBuilder()
與Program.cs
:var builder = WebApplication.CreateBuilder(args); builder.Services.AddApplicationInsightsTelemetry(); // Add this line of code to enable Application Insights. builder.Services.AddServiceProfiler(); // Add this line of code to enable Profiler builder.Services.AddControllersWithViews(); var app = builder.Build();
提取最新的 ASP.NET Core 組建/執行階段映像
瀏覽至 .NET Core 6.0 範例目錄:
cd examples/EnableServiceProfilerForContainerAppNet6
提取最新的 ASP.NET Core 映像:
docker pull mcr.microsoft.com/dotnet/sdk:6.0 docker pull mcr.microsoft.com/dotnet/aspnet:6.0
新增您的 Application Insights 金鑰
透過 Azure 入口網站中的 Application Insights 資源,記下 Application Insights 連接字串。
開啟
appsettings.json
並新增 Application Insights 連接字串到此程式碼區段:{ "ApplicationInsights": { "InstrumentationKey": "Your connection string" } }
組建和執行 Docker 映像
查看 Docker 檔案。
組建範例映像:
docker build -t profilerapp .
執行容器:
docker run -d -p 8080:80 --name testapp profilerapp
透過瀏覽器檢視容器
若要訪問端點,您有兩個選項:
請在瀏覽器中訪問
http://localhost:8080/weatherforecast
。使用 curl:
curl http://localhost:8080/weatherforecast
檢查記錄
您可以選擇檢查本機記錄,查看分析作業是否已經完成。
docker logs testapp
在本機記錄中,注意下列事件:
Starting application insights profiler with connection string: your-connection string # Double check the connection string
Service Profiler session started. # Profiler started.
Finished calling trace uploader. Exit code: 0 # Uploader is called with exit code 0.
Service Profiler session finished. # A profiling session is completed.
故障排除
如果您無法從應用程式找到追蹤,請考慮遵循此 疑難解答指南中的步驟。
檢視 .NET Profiler 追蹤
等待 2 至 5 分鐘,讓系統可將事件彙總至 Application Insights。
在 Application Insights 資源中開啟 [效能] 窗格。
追蹤程序完成之後,[分析工具追蹤] 按鈕隨即出現。
清除資源
執行下列命令可停止範例專案:
docker rm -f testapp