演習 - .NET 8 でテレメトリを拡張する

完了

現在の eShopLite アプリでは、OpenTelemetry によって提供される既定のテレメトリが使用されています。 テレメトリ データにカスタム メトリックとカスタム属性を追加することで、テレメトリを拡張できます。 この機能を使用すると、テレメトリ データにさらに多くのコンテキストを追加したり、Application Insights でより強力なクエリを作成したりできます。

この演習では、アプリに新しいメトリックを追加し、監視アプリでそれらを表示する方法を確認します。

カスタム メトリックを作成する

時間の経過に伴う在庫の変化をより詳細に把握するために、カスタム メトリックを作成します。

  1. Visual Studio Code の [エクスプローラー] ペインで、Products フォルダーを右クリックし、[新しいファイル] を選択します。

  2. [ファイル名] フィールドに「ProductsMetrics.cs」と入力します。

  3. テキスト エディターで、コードを次の例に置き換えます。

    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 という新しいメトリックが作成されます。 これは、製品サービスを通じて変更された在庫の量を追跡するメトリックです。

  4. Ctrl+S を選択して、ファイルを保存します。

  5. [エクスプローラー] ペインの Products フォルダーで、Program.cs を選択します。

  6. AddObservability のコードをこのコードに置き換えます。

    builder.Services.AddObservability("Products", builder.Configuration, ["eShopLite.Products"]);
    
    // Register the metrics service.
    builder.Services.AddSingleton<ProductsMetrics>();
    

    このコードにより、ProductsMetrics クラスが依存関係挿入コンテナーに追加されます。

  7. Ctrl+S を選択して、ファイルを保存します。

  8. [エクスプローラー] ペインの Products フォルダーで、Endpoint フォルダーを展開し、ProductEndpoints.cs を選択します。

  9. 既存の在庫更新 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 メソッドを呼び出して、新しい在庫量によってメトリックを増分します。

  10. Ctrl+S を選択して、ファイルを保存します。

OpenTelemetry にメトリックを追加する

次に、OpenTelemetry にメトリックを追加して、監視ツールにエクスポートできるようにします。

  1. [エクスプローラー] ペインの Diagnostics フォルダーで、DiagnosticServiceCollectionExtensions を選択します。

  2. 新しいパラメーターを受け入れるように AddObservability メソッドを変更します。

    public static IServiceCollection AddObservability(this IServiceCollection services,
        string serviceName,
        IConfiguration configuration,
        string[]? meeterNames = null)
    
  3. Prometheus エクスポーター行の下に、次のコードを追加します。

    .AddPrometheusExporter();
    
    // add any additional meters provided by the caller
    if (meeterNames != null)
    {
      foreach (var name in meeterNames)
      {
        metrics.AddMeter(name);
      }
    }
    
  4. Ctrl+S を選択して、ファイルを保存します。

Prometheus で新しいメトリックを表示する

  1. 下部の [ターミナル] ペインで、dotnet-observability/eShopLite フォルダーに移動します。

    cd ..
    
  2. アプリ コンテナーを更新します。

    dotnet publish /p:PublishProfile=DefaultContainer 
    
  3. dotnet-observability フォルダーに移動し、次のように Docker でアプリを起動します。

    cd ..
    docker compose up
    
  4. ブラウザーで http://localhost:32000eShopLite アプリを開きます。

  5. [Products] ページに移動し、複数の製品の在庫量を変更します。

  6. Prometheus ダッシュボードで http://localhost:9090 を開きます。

  7. 検索ボックスに eshoplite_products_stock_change_total メトリックを入力し、[Execute] を選択します。

    それがテーブルに表示されます。

  8. [グラフ] タブを選択します。時間の経過に伴う在庫量の変化がわかります。

    Screenshot that shows Prometheus showing the new custom metric on a graph.

  9. [ターミナル] ペインで、Ctrl+C キーを押してアプリを停止します。