练习 - 将 OpenTelemetry 添加到云原生应用程序

已完成

在本练习中,你将向解决方案添加新的诊断项目 eShopLite 。 你将了解如何包含 OpenTelemetry NuGet 包,然后向 产品 服务添加可观测性。

打开开发环境并创建 Azure 资源

可以选择使用托管练习的 GitHub codespace,或在 Visual Studio Code 中本地完成练习。

若要使用 codespace,请使用此 Codespace 创建模板创建预配置的 GitHub codespace。

GitHub 创建和配置 codespace 时,此步骤需要几分钟时间。 完成此过程后,你将看到练习的代码文件。 用于本模块其余部分的代码位于 /dotnet-observability 目录中。

要使用 Visual Studio Code,请将 https://github.com/MicrosoftDocs/mslearn-dotnet-cloudnative 存储库克隆到本地计算机。 然后:

  1. 安装任何 系统要求 以在 Visual Studio Code 中运行开发容器。
  2. 确保 Docker 正在运行。
  3. 在新的 Visual Studio Code 窗口中,打开克隆存储库的文件夹
  4. Ctrl+Shift+P 打开命令面板。
  5. 搜索:>开发容器:在容器中重新生成和重新打开
  6. 从下拉列表中选择 eShopLite - dotnet-observability 。 Visual Studio Code 将在本地创建你的开发容器。

将诊断项目添加到解决方案

eShopLite 应用添加可观测性的第一步是向解决方案中引入一个新的诊断项目。 此项目包含将用于向应用添加可观测性的所有 OpenTelemetry 包和配置。

  1. 在 Visual Studio Code 命令面板中,输入 >.NET:打开解决方案
  2. 选择“dotnet-observability/eShopLite/eShopLite.sln”
  3. “解决方案资源管理器”中,在 “资源管理器 ”窗格底部,右键单击 eShopLite 解决方案,然后选择“ 新建项目”。
  4. “选择模板以创建新的 .NET 项目”对话框中,选择“类库”(Common,Library)。
  5. “名称” 字段中,输入 “诊断”。
  6. “项目将创建于” 下拉列表中,选择 “默认目录”

添加 OpenTelemetry 包

现在,将 OpenTelemetry 包添加到新的诊断项目。

  1. 通过使用 Visual Studio Code 底部的 “终端 ”窗格,转到 “诊断 ”项目文件夹:

    cd dotnet-observability/eShopLite/Diagnostics
    
  2. dotnet add运行以下命令:

    dotnet add package OpenTelemetry.Exporter.Console
    dotnet add package OpenTelemetry.Extensions.Hosting
    dotnet add package OpenTelemetry.Instrumentation.AspNetCore
    dotnet add package OpenTelemetry.Instrumentation.EventCounters --prerelease
    dotnet add package OpenTelemetry.Instrumentation.Runtime
    dotnet add package OpenTelemetry.Instrumentation.SqlClient --prerelease
    dotnet add package OpenTelemetry.Instrumentation.Http
    
  3. “资源管理器 ”窗格中,展开 “诊断 ”文件夹,然后选择 Diagnostics.csproj

  4. Project Sdk 顶部更改为:

    <Project Sdk="Microsoft.NET.Sdk.Web">
    

    上述代码允许在代码中使用 IConfiguration 类。

  5. <PropertyGroup>中添加输出类型:

    <OutputType>Library</OutputType>
    

    上述代码可确保项目生成为库。 否则,编译器需要具有 main 方法的 Program.cs 文件。

添加代码以使用 OpenTelemetry

添加 OpenTelemetry 包后,现在引入代码来使用它们。

  1. “资源管理器 ”窗格中,右键单击 Class1.cs 文件,然后选择“ 重命名”。

  2. 将文件重命名为 DiagnosticServiceCollectionExtensions.cs

  3. 将文件中的代码替换为以下代码:

    using OpenTelemetry.Metrics;
    using OpenTelemetry.Resources;
    using OpenTelemetry.Trace;
    
    namespace Microsoft.Extensions.DependencyInjection;
    
    public static class DiagnosticServiceCollectionExtensions
    {
      public static IServiceCollection AddObservability(this IServiceCollection services,
          string serviceName,
          IConfiguration configuration)
      {
        // create the resource that references the service name passed in
        var resource = ResourceBuilder.CreateDefault().AddService(serviceName: serviceName, serviceVersion: "1.0");
    
        // add the OpenTelemetry services
        var otelBuilder = services.AddOpenTelemetry();
    
        otelBuilder
            // add the metrics providers
            .WithMetrics(metrics =>
            {
              metrics
                .SetResourceBuilder(resource)
                .AddRuntimeInstrumentation()
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .AddEventCountersInstrumentation(c =>
                {
                  c.AddEventSources(
                          "Microsoft.AspNetCore.Hosting",
                          "Microsoft-AspNetCore-Server-Kestrel",
                          "System.Net.Http",
                          "System.Net.Sockets");
                })
                .AddMeter("Microsoft.AspNetCore.Hosting", "Microsoft.AspNetCore.Server.Kestrel")
                .AddConsoleExporter();
    
            })
            // add the tracing providers
            .WithTracing(tracing =>
            {
              tracing.SetResourceBuilder(resource)
                          .AddAspNetCoreInstrumentation()
                          .AddHttpClientInstrumentation()
                          .AddSqlClientInstrumentation();
            });
    
        return services;
      }
    }
    
  4. “终端 ”窗格中,运行以下命令以生成项目:

    dotnet build
    

    此时应会看到如下例所示的输出:

    Build succeeded.
        0 Warning(s)
        0 Error(s)
    
  5. 诊断项目现已可供产品服务使用。

  6. “资源管理器 ”窗格的 “解决方案资源管理器”下,右键单击 “产品 ”项目,然后选择“ 添加项目引用”。

  7. 选择“诊断”

  8. “资源管理器 ”窗格中,展开“ 产品 ”文件夹,然后选择 Program.cs

  9. 在代码注释 // Add observability code here下,添加对 Diagnostics 方法的调用:

    builder.Services.AddObservability("Products", builder.Configuration);
    
  10. “终端 ”窗格中,转到 “产品 ”文件夹:

    cd ../Products
    
  11. 运行以下命令以生成项目:

    dotnet build
    

    此时应会看到如下例所示的输出:

    Build succeeded.
        0 Warning(s)
        0 Error(s)
    

更新 Docker 设置并运行应用

  1. “终端 ”窗格中,转到 dotnet-observability 文件夹的根目录:

    cd ..
    dotnet publish /p:PublishProfile=DefaultContainer
    
  2. 运行以下 Docker 命令:

    cd /workspaces/mslearn-dotnet-cloudnative/dotnet-observability/
    docker compose up 
    

    后端(产品 服务)和前端(应用商店 服务)容器应生成。 然后,应用将启动。

  3. 如果要在代码空间中执行此练习,请选择 Visual Studio Code 窗口底部的 “端口 ”选项卡。 选择前端服务旁的“在浏览器中打开”链接。

  4. 如果您在 Visual Studio Code 本地执行此练习,请在新的浏览器选项卡中打开应用程序 http://localhost:32000

  5. 在应用中,选择导航栏中的 “产品 ”。

    显示 eShopLite 应用中的“产品”页的屏幕截图。该页显示具有名称、说明和价格的产品列表,以及用于更新库存的按钮。

  6. 为多个产品选择 “更新库存 ”。 然后,在对话框中更改股票值,然后选择“ 更新”。

  7. 选择 “终端 ”选项卡并滚动浏览消息。 请注意,OpenTelemetry 中存在如下消息:

    backend-1   | Export ec.Microsoft-AspNetCore-Server-Kestrel.connection-queue-length, Meter: OpenTelemetry.Instrumentation.EventCounters/1.5.1.1
    backend-1   | (2023-11-09T19:55:14.8933518Z, 2023-11-09T20:04:44.8596671Z] http.request.method: PUT http.response.status_code: 200 http.route: /api/Stock/{id} network.protocol.name: http network.protocol.version: 1.1 url.scheme: http Histogram      
    backend-1   | Value: Sum: 0.05144170000000001 Count: 4 Min: 0.0039736 Max: 0.0359739
    
  8. Ctrl+C 停止应用。

已成功将 OpenTelemetry 添加到 产品 服务。 在下一单元中,你将了解如何通过在 Prometheus 和 Grafana 等工具上查看遥测数据来更好地利用遥测数据。