练习 - 在云原生应用程序中使用 OpenTelemetry 数据

已完成

在本练习中,你可以更好地了解应用中 OpenTelemetry 生成的所有数据。 完成向应用商店服务添加诊断功能。 在此基础上,将 Prometheus 和 Grafana 添加到 eShopLite 服务中,并查看正在捕获的一些指标。 下一步是添加 Zipkin 并查看分布式跟踪。 最后,将 Application Insights 添加到应用,并使用它来查看数据。

添加 Prometheus 和 Grafana

Prometheus 和 Grafana 提供 Docker 映像,以便轻松地将它们添加到项目中。 将其包含在解决方案根目录中 docker-compose.yml 文件中。

  1. “资源管理器 ”窗格中,选择 docker-compose.yml 文件。

  2. 将此 YAML 添加到文件底部:

      prometheus:
        image: prom/prometheus
        container_name: prometheus
        command:
          - '--config.file=/etc/prometheus/prometheus.yml'
        ports:
          - 9090:9090
        restart: unless-stopped
        volumes:
          - ./prometheus:/etc/prometheus
    
      grafana:
        image: grafana/grafana
        container_name: grafana
        ports:
          - 3000:3000
        restart: unless-stopped
        environment:
          - GF_SECURITY_ADMIN_USER=admin
          - GF_SECURITY_ADMIN_PASSWORD=grafana
        volumes:
          - ./grafana/datasource:/etc/grafana/provisioning/datasources
    

前面的 Docker yaml 添加了两个新服务 :PrometheusGrafana。 Prometheus 部分配置容器以在端口 9090 上响应。 它映射prometheus文件夹,期望有一个prometheus.yml文件。 Grafana 节配置容器以在端口 3000 上响应。 它将 grafana 文件夹中的三个文件夹进行映射。

配置 Prometheus

需要配置 Prometheus,以便知道在何处收集指标。 将 prometheus.yml 文件添加到 prometheus 文件夹。

  1. “资源管理器 ”窗格中,右键单击 dotnet-observability 文件夹,然后选择“ 新建文件夹”。

  2. 在名称字段中,输入 prometheus

  3. “资源管理器 ”窗格中,右键单击 prometheus 文件夹,然后选择“ 新建文件”。

  4. 在名称字段中,输入 prometheus.yml

  5. 在文件编辑器中,输入以下 YAML:

    global:
      scrape_interval: 1s
    
    scrape_configs:
      - job_name: 'products'
        static_configs:
          - targets: ['backend:8080']
      - job_name: 'store'
        static_configs:
          - targets: ['frontend:8080']
    

    前面的 YAML 将 Prometheus 配置为从 后端前端 服务中抓取指标。 当应用在 Docker 中运行时,主机名是服务名称。

  6. 选择 Ctrl+S 以保存文件。

配置 Grafana

需要配置 Grafana,以便知道在何处收集指标。

  1. “资源管理器 ”窗格中,右键单击 dotnet-observability 文件夹,然后选择“ 新建文件夹”。

  2. 在名称字段中,输入 grafana

  3. 右键单击 grafana 文件夹,然后选择“ 新建文件夹”。

  4. 在名称字段中,输入 数据源

  5. 右键单击 grafana 文件夹,然后选择“ 新建文件夹”。

  6. 在名称字段中,输入 仪表板

  7. 展开 grafana 文件夹,右键单击 数据源 文件夹,然后选择“ 新建文件”。

  8. 在名称字段中,输入 datasource.yml

  9. 在编辑器选项卡上,输入以下 YAML:

    apiVersion: 1
    
    datasources:
    - name: Prometheus
      type: prometheus
      url: http://prometheus:9090 
      isDefault: true
      access: proxy
      editable: true
    

    前面的 YAML 将 Grafana 配置为使用 Prometheus 作为数据源。

  10. 选择 Ctrl+S 以保存文件。

更新 ASP.NET Core 应用以公开 Prometheus 的指标

现在,诊断项目仅配置为向控制台公开指标。 你将更新项目以改为向 Prometheus 公开指标。

  1. 在底部的 “终端 ”窗格中,转到 “诊断” 文件夹。

  2. 运行以下命令:

    cd .\eShopLite\Diagnostics\ 
    
  3. 移除 OpenTelemetry.Exporter.Console 包:

    dotnet remove package OpenTelemetry.Exporter.Console
    
  4. 添加 OpenTelemetry.Exporter.Prometheus.AspNetCore 包:

    dotnet add package OpenTelemetry.Exporter.Prometheus.AspNetCore --prerelease
    
  5. “资源管理器 ”窗格中,展开 “诊断 ”文件夹,然后选择 DiagnosticServiceCollectionExtensions.cs

  6. 将控制台导出程序 .AddConsoleExporter(); 替换为以下代码:

    .AddPrometheusExporter();
    
  7. 在文件的底部,在最后 }一个代码之前,添加以下代码:

    public static void MapObservability(this IEndpointRouteBuilder routes)
    {
      routes.MapPrometheusScrapingEndpoint();
    }
    

    此代码会将 Prometheus 抓取终结点添加到在应用中包含此项的每个服务。 这允许 Prometheus 从 http://service/metrics中抓取指标。

  8. 选择 Ctrl+S 以保存文件。

在应用商店服务中公开指标

应用当前仅配置为公开 产品 服务的指标。 你还将更新应用以公开“商店”服务的指标

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

  2. 选择“诊断”

  3. “资源管理器 ”窗格中,展开 “应用商店 ”文件夹,然后选择 Program.cs

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

    builder.Services.AddObservability("Store", builder.Configuration);
    
  5. app.Run() 方法之前,添加以下代码:

    app.MapObservability();
    

    此方法将 Prometheus 抓取终结点添加到 Microsoft Store 服务。

  6. 选择 Ctrl+S 以保存文件。

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

  8. app.Run() 方法之前,添加以下代码:

    app.MapObservability();
    

    此方法将 Prometheus 抓取终结点添加到 产品 服务。

  9. 选择 Ctrl+S 以保存文件。

测试新的可观测性特征

现在测试添加到应用的新可观测性功能。

  1. 在底部的 “终端 ”窗格中,转到 dotnet-observability/eShopLite 文件夹。

    cd ..
    
  2. 更新应用容器。

    dotnet publish /p:PublishProfile=DefaultContainer 
    
  3. 转到 dotnet-observability 文件夹,并使用 Docker 启动应用:

    cd ..
    docker compose up
    
  4. 在“端口”选项卡上,选择“在浏览器中打开 Prometheus”(9090)。 如果在 Visual Studio Code 中本地运行,请打开浏览器,然后在新选项卡上转到 Prometheus 应用 http://localhost:9090

  5. 在顶部菜单中,选择“ 状态 ”,然后选择“ 目标”。

    显示配置的 Prometheus 应用的屏幕截图,其中显示了 eShopLite 应用的运行状况。

    你应会看到“产品”和“商店”服务列为“UP”。

  6. 在“端口”选项卡上,选择“在浏览器中打开 Grafana”(3000)。 如果在 Visual Studio Code 中本地运行,请打开浏览器,然后在新选项卡上转到 Grafana 应用 http://localhost:3000

  7. 输入用户名 管理员

  8. 输入密码 grafana

  9. 选择“ 创建第一个仪表板”。

  10. 选择“ 导入仪表板”。

  11. 在新选项卡上,转到 GitHub 并打开 ASP.NET Core 仪表板 json 文件。

  12. 复制原始文件

  13. 通过仪表板 JSON 模型文本框将 JSON 粘贴到“导入”中。

  14. 选择 加载

  15. “Prometheus 数据源 ”下拉列表中,选择 “Prometheus”。

  16. 选择“导入” 。

    显示 Grafana 中 ASP.NET 仪表板的屏幕截图。

    应会看到一个仪表板,其中显示了产品和应用商店服务的指标。 选择要在两个服务之间更改的作业。

  17. “终端 ”窗格中,选择 Ctrl+C 以停止应用。

添加 Zipkin

现在,通过添加 Zipkin 来扩展应用的跟踪功能。 如前所述,将 Zipkin 容器添加到应用,并将其配置为连接到 OpenTelemetry 收集器。 然后将 OpenTelemetry Zipkin 导出程序添加到应用。

  1. “资源管理器”窗格中,选择 dotnet-observability 文件夹中docker-compose.yml文件。

  2. prometheus 中为 zipkin 添加 depends_onfrontend

    depends_on: 
      - backend
      - prometheus
      - zipkin 
    
  3. prometheusdepends_on 中添加 backend

     depends_on: 
       - prometheus
    
  4. 将 Zipkin 的环境变量添加到 BOTHfrontendbackend

    environment: 
      - ZIPKIN_URL=http://zipkin:9411    
    

    这两个服务应如下所示:

    frontend:
      image: storeimage
      build:
        context: .
        dockerfile: ./eShopLite/Store/Dockerfile
      environment: 
        - ProductEndpoint=http://backend:8080
        - ZIPKIN_URL=http://zipkin:9411
      ports:
        - "32000:8080"
      depends_on: 
        - backend
        - prometheus
        - zipkin
    
    backend:
      image: productservice
      build: 
        context: .
        dockerfile: ./eShopLite/Products/Dockerfile
      environment: 
        - ZIPKIN_URL=http://zipkin:9411
    
      ports: 
        - "32001:8080"
      depends_on: 
        - prometheus    
    
  5. 将此 YAML 添加到文件底部:

      zipkin:
        image: openzipkin/zipkin
        ports:
          - 9411:9411
    

    前面的 YAML 将 Zipkin 容器添加到应用。 它将 Zipkin 容器配置为在端口 9411 上做出响应。

  6. 选择 Ctrl+S 以保存文件。

  7. “终端 ”窗格中,转到 “诊断” 文件夹。

    cd ./eShopLite/Diagnostics/
    
  8. 添加 Zipkin 导出包。

    dotnet add package OpenTelemetry.Exporter.Zipkin --prerelease
    
  9. “资源管理器 ”窗格中,展开 “诊断 ”文件夹,然后选择 DiagnosticServiceCollectionExtensions.cs

  10. 在跟踪提供程序的底部,添加 Zipkin:

    // add the tracing providers
    .WithTracing(tracing =>
    {
      tracing.SetResourceBuilder(resource)
                  .AddAspNetCoreInstrumentation()
                  .AddHttpClientInstrumentation()
                  .AddSqlClientInstrumentation()
                  .AddZipkinExporter(zipkin =>
                  {
                    var zipkinUrl = configuration["ZIPKIN_URL"] ?? "http://zipkin:9411";
                    zipkin.Endpoint = new Uri($"{zipkinUrl}/api/v2/spans");
                  });
    });
    
  11. 选择 Ctrl+S 以保存文件。

  12. 在底部的 “终端 ”窗格中,转到 dotnet-observability/eShopLite 文件夹。

    cd ..
    
  13. 更新应用容器。

    dotnet publish /p:PublishProfile=DefaultContainer 
    
  14. 转到 dotnet-observability 文件夹,并使用 Docker 启动应用:

    cd ..
    docker compose up
    
  15. 在“端口”选项卡上,选择“在浏览器中打开 Prometheus”(9090)。 如果在 Visual Studio Code 中本地运行,请打开新的浏览器选项卡并转到 Zipkin 应用 http://localhost:9411

  16. 在菜单上,选择 “依赖项”。

    屏幕截图显示了 Zipkin,其中显示了向产品服务发送请求的 eShopLite App Store 的依赖项。

  17. “终端 ”窗格中,选择 Ctrl+C 以停止应用。

添加 Application Insights

最后一步是将 Application Insights 添加到应用。

在 Azure 中创建 Application Insights 资源

  1. “终端 ”窗格中,登录到 Azure。

    az login --use-device-code
    
  2. 查看所选的 Azure 订阅。

    az account show -o table
    

    如果选择了错误的订阅,请使用 az account set 命令选择正确的订阅。

  3. 添加 Application Insights 扩展。

    az extension add -n application-insights
    
  4. 创建 Application Insights 资源。

    az monitor app-insights component create --app eShopLiteInsights --___location eastus --kind web -g eShopLite
    

    你应该会看到以下输出:

    {
      "appId": "00001111-aaaa-2222-bbbb-3333cccc4444",
      "applicationId": "eShopLiteInsights",
      "applicationType": "web",
      "connectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://eastus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/",
      "creationDate": "2023-11-10T16:50:00.950726+00:00",
      "disableIpMasking": null,
      "etag": "\"3a02952a-0000-0100-0000-654e5f380000\"",
      "flowType": "Bluefield",
      "hockeyAppId": null,
      "hockeyAppToken": null,
      "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/eShopLite/providers/microsoft.insights/components/eShopLiteInsights",
      "immediatePurgeDataOn30Days": null,
      "ingestionMode": "ApplicationInsights",
      "instrumentationKey": "00000000-0000-0000-0000-000000000000",
      "kind": "web",
      "___location": "eastus",
      "name": "eShopLiteInsights",
      "privateLinkScopedResources": null,
      "provisioningState": "Succeeded",
      "publicNetworkAccessForIngestion": "Enabled",
      "publicNetworkAccessForQuery": "Enabled",
      "requestSource": "rest",
      "resourceGroup": "eShopLite",
      "retentionInDays": 90,
      "samplingPercentage": null,
      "tags": {},
      "tenantId": "aaaabbbb-0000-cccc-1111-dddd2222eeee",
      "type": "microsoft.insights/components"
    }
    

    在上述返回的 JSON 中,复制 connectionString,但不包括 "。 例如:

    InstrumentationKey=b851fa75-85a2-42f7-bb6f-413725d9d8ba;IngestionEndpoint=https://eastus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/

  5. “资源管理器 ”窗格中,选择 docker-compose.yml 文件。

  6. 您添加一个环境变量,以供诊断项目用于连接到 Application Insights。 将此 YAML 添加到 应用商店 服务:

    environment:
      - APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=b851fa75-85a2-42f7-bb6f-413725d9d8ba;IngestionEndpoint=https://eastus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/
    

    将前面的连接字符串替换为从 Azure CLI 复制的连接字符串。

  7. 产品 服务重复这些步骤。 最终 YAML 应如下所示:

      frontend:
        image: storeimage
        build:
          context: .
          dockerfile: ./eShopLite/Store/Dockerfile
        environment: 
          - ProductEndpoint=http://backend:8080
          - ZIPKIN_URL=http://zipkin:9411
          - APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=b851fa75-85a2-42f7-bb6f-413725d9d8ba;IngestionEndpoint=https://eastus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/
        ports:
          - "32000:8080"
        depends_on: 
          - backend
          - prometheus
          - zipkin
    
      backend:
        image: productservice
        build: 
          context: .
          dockerfile: ./eShopLite/Products/Dockerfile
        environment: 
          - ZIPKIN_URL=http://zipkin:9411
          - APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=b851fa75-85a2-42f7-bb6f-413725d9d8ba;IngestionEndpoint=https://eastus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/
    
    
  8. 选择 Ctrl+S 以保存文件。

  9. “终端 ”窗格中,转到 “诊断” 文件夹。

    cd .\eShopLite\Diagnostics\ 
    
  10. 添加 Application Insights 导出程序包。

    dotnet add package Azure.Monitor.OpenTelemetry.AspNetCore --prerelease
    
  11. “浏览 ”窗格中,选择“ 诊断” 文件夹,然后选择 DiagnosticServiceCollectionExtensions.cs

  12. 在文件的顶部,添加以下 using 语句:

    using Azure.Monitor.OpenTelemetry.AspNetCore;
    
  13. 之后 var otelBuilder = services.AddOpenTelemetry();,添加以下代码:

    if (!string.IsNullOrEmpty(configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
    {
      otelBuilder.UseAzureMonitor();
    }
    
  14. 选择 Ctrl+S 以保存文件。

  15. 在底部的 “终端 ”窗格中,转到 dotnet-observability/eShopLite 文件夹。

    cd ..
    
  16. 更新应用容器。

    dotnet publish /p:PublishProfile=DefaultContainer 
    
  17. 转到 dotnet-observability 文件夹,并使用 Docker 启动应用:

    cd ..
    docker compose up
    
  18. 使用用于登录到 Azure CLI 的相同凭据登录到 Azure 门户。

  19. Azure 门户中,选择“资源组”。

  20. 选择 eShopLite 资源组。

  21. 选择 eShopLiteInsights Application Insights 资源。

  22. 选择 应用程序仪表板

    显示 Application Insights 的屏幕截图,其中显示了 eShopLite 应用的运行状况。

  23. 若要查看指标的更改,请转到 eShopLite 应用并更改库存。 然后刷新 Application Insights 仪表板。

  24. 终端 窗格中,按 Ctrl+C 停止应用。