练习 - 在 .NET 8 中扩展遥测

已完成

当前 eShopLite 应用使用 OpenTelemetry 提供的默认遥测。 可以通过向遥测数据添加自定义指标和自定义属性来扩展遥测。 利用此功能,可以向遥测数据添加更多上下文,并在 Application Insights 中创建更强大的查询。

在本练习中,你将向应用添加新指标,并了解如何在可观测性应用中查看它们。

创建自定义指标

你希望更清楚地了解存货随时间推移的变化,以便创建自定义指标。

  1. 在 Visual Studio Code 的“资源管理器”窗格中,右键单击“产品”文件夹,然后选择“新建文件”。

  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. 在“资源管理器”窗格的“产品”文件夹中,选择“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. 在“资源管理器”窗格中的“产品”文件夹中,展开“终结点”文件夹,然后选择“产品Endpoints.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. 在“资源管理器”窗格的“诊断”文件夹中,选择“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:32000 打开 eShopLite 应用。

  5. 转到“产品”页,然后更改多个产品的库存量。

  6. 打开 http://localhost:9090 处的 Prometheus 仪表板。

  7. 在搜索框中,输入 eshoplite_products_stock_change_total 指标,然后选择“执行”。

    你应会看到它列在表中。

  8. 选择“图形”选项卡。你应会看到库存量随时间而变化。

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

  9. 在“终端”窗格中,按 Ctrl+C 停止应用。