練習 - 在 .NET 8 中擴充遙測
目前的 eShopLite 應用程式會使用 OpenTelemetry 所提供的預設遙測。 您可以將自定義計量和自定義屬性新增至遙測數據,以擴充遙測。 這項功能可讓您將更多內容新增至遙測數據,並在 Application Insights 中建立更強大的查詢。
在此練習中,您會將新的計量新增至應用程式,並瞭解如何在可檢視性應用程式中檢視它們。
建立自訂計量
您想要更清楚瞭解股票隨著時間變化的方式,因此您可以建立自定義計量。
在 EXPLORER 窗格中,滑鼠右鍵點擊 產品資料夾,然後選取 新增檔案。
在 [ 檔名] 欄位中,輸入 ProductsMetrics.cs。
在文字編輯器中,以下列範例取代程序代碼:
using System; using System.Diagnostics.Metrics; public class ProductsMetrics { private readonly Counter<int> _serviceCalls; private readonly Counter<int> _stockChange; public ProductsMetrics(IMeterFactory meterFactory) { var meter = meterFactory.Create("eShopLite.Products"); _stockChange = meter.CreateCounter<int>("eshoplite.products.stock_change", unit: "{stock}", description: "Amount of stock being changed through the product service."); } public void StockChange(int quantity) { _stockChange.Add(quantity); } }
上述程式代碼會建立名為
eshoplite.products.stock_change
的新計量。 此計量會追蹤透過產品服務變更的庫存量。選擇 Ctrl+S 以儲存檔案。
在 [檔案總管] 窗格的 Products 資料夾中,選取 [Program.cs]。
將
AddObservability
代碼替換為此代碼:builder.Services.AddObservability("Products", builder.Configuration, ["eShopLite.Products"]); // Register the metrics service. builder.Services.AddSingleton<ProductsMetrics>();
此程式代碼會將
ProductsMetrics
類別新增至相依性插入容器。選擇 Ctrl+S 以儲存檔案。
在[EXPLORER]窗格的[Products]資料夾中,展開[Endpoint]資料夾,然後選取[ProductEndpoints.cs]。
使用下列程式代碼取代現有的庫存更新
MapPut
端點:stock.MapPut("/{id}", async (int id, int stockAmount, ProductDataContext db, ProductsMetrics metrics) => { // Increment the stock change metric. metrics.StockChange(stockAmount); var affected = await db.Product .Where(model => model.Id == id) .ExecuteUpdateAsync(setters => setters .SetProperty(m => m.Stock, stockAmount) ); return affected == 1 ? Results.Ok() : Results.NotFound(); })
您使用相依性插入將
ProductsMetrics
類別新增至端點。 接著,您會呼叫StockChange
方法,以新的庫存量遞增計量。選擇 Ctrl+S 以儲存檔案。
將計量新增至 OpenTelemetry
您現在將計量新增至 OpenTelemetry,使其可以匯出至您的可檢視性工具。
在 [檔案總管] 窗格的 Diagnostics 資料夾中,選取 [DiagnosticServiceCollectionExtensions]。
將
AddObservability
方法更改為接受新的參數:public static IServiceCollection AddObservability(this IServiceCollection services, string serviceName, IConfiguration configuration, string[]? meeterNames = null)
在 Prometheus 匯出程式行下方,新增下列程式代碼:
.AddPrometheusExporter(); // add any additional meters provided by the caller if (meeterNames != null) { foreach (var name in meeterNames) { metrics.AddMeter(name); } }
選擇 Ctrl+S 以儲存檔案。
在 Prometheus 中檢視新的計量
在底部的 [終端機 ] 窗格中,移至 dotnet-observability/eShopLite 資料夾。
cd ..
更新應用程式容器。
dotnet publish /p:PublishProfile=DefaultContainer
移至 dotnet-observability 資料夾,並使用 Docker 啟動應用程式:
cd .. docker compose up
在瀏覽器中開啟位於 eShopLite 的應用程式
http://localhost:32000
。移至 [ 產品] 頁面,並變更數個產品的庫存量。
開啟 Prometheus 儀錶板
http://localhost:9090
。在搜尋方塊中
eshoplite_products_stock_change_total
,輸入計量,然後選取 [ 執行]。您應該會看到它列在數據表中。
選取 [圖形] 標籤。您應該會看到庫存數量隨時間變更。
在 [終端機 ] 窗格中,按 Ctrl+C 以停止應用程式。