向云原生应用程序添加可观测性

已完成

现在,你已了解可观测性的重要性,你将了解如何将其包含在云原生应用程序中。 为执行此步骤,请将 OpenTelemetry 添加到应用。

将 OpenTelemetry 添加到应用

.NET 具有丰富的内置可观测性工具生态系统,可生成日志记录、指标和跟踪数据。 可以使用这些工具向云原生应用程序添加可观测性。 这些库包括:

  • 日志记录Microsoft.Extensions.Logging.ILogger
  • 指标System.Diagnostics.Metrics.Meter
  • 跟踪System.Diagnostics.ActivitySystem.Diagnostics.ActivitySource

OpenTelemetry 会使用上述所有遥测数据,但云原生应用首先需要通过 NuGet 包添加 OpenTelemetry 支持。 这些包可以分为三个组:

类别 程序包 说明
核心 API OpenTelemetry 提供核心 OpenTelemetry 功能的主库。
核心 API OpenTelemetry.Extensions.Hosting 提供用于在 ASP.NET Core 主机中自动启动和停止 OpenTelemetry 跟踪的扩展方法。
检测 OpenTelemetry.Instrumentation.AspNetCore ASP.NET Core 应用程序的检测。 此包会收集有关应用的大量指标,而无需编写任何代码。
出口商 OpenTelemetry.Exporter.Console 通过控制台的导出程序,应用可以将遥测数据写出到控制台。

云原生应用中可以包含更多的检测和导出程序包。 有关详细信息,请参阅使用 OpenTelemetry 的 .NET 可观测性。 根据要构建的应用类型,可以添加与你最相关的包。

本模块重点介绍如何将 OpenTelemetry 与 eShopLite 云原生应用配合使用。 由于此应用是使用 .NET Core 和 Blazor WebAssembly 构建的,因此,这意味着所有代码示例都是基于利用依赖项注入的。

显示应用的不同 OpenTelemetry 组件的关系图。

可以选择将所有 OpenTelemetry 包同时包含在微服务应用中的“产品”和“Store”服务中。 但在实际应用中,你或拥有更多的服务。 将所有这些包添加到每个服务会涉及不必要的重复。 更好的方法是将新的诊断项目添加到解决方案中,然后任何微服务都可以引用这些项目来观察。

下面是一些用于创建方法 AddObservability 的示例代码,微服务可以调用该方法来使用 OpenTelemetry:

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;
  }

  // Add the Prometheus endpoints to your service, this will expose the metrics at http://service/metrics
  public static void MapObservability(this IEndpointRouteBuilder routes)
  {
    routes.MapPrometheusScrapingEndpoint();
  }
}

该方法将返回一个 IServiceCollection 类,可将其作为服务添加到 ASP.NET Core WebApplicationBuilder

然后,此操作会创建一个变量 var otelBuilder = services.AddOpenTelemetry() 来存储 OpenTelemetry 生成器。 然后,代码可以将指标和跟踪添加到 otelBuilder

例如,此配置添加了以下项的检测:

  • ASP.NET Core
  • C# 运行时
  • HttpCLient
  • Kestrel Web 服务器

这些指标显示在控制台中。 .AddConsoleExporter() 方法将导出程序添加到生成器。

它还会将跟踪添加到控制台,用于:

  • ASP.NET Core
  • HttpClient
  • SQL 客户端

最后一行会返回 IServiceCollection 类。

完成诊断项目后,只需向项目添加引用并向服务添加一行代码即可。 例如,要在“产品”服务中包含 OpenTelemetry,请在 Product.csproj 文件中添加项目引用:

<ProjectReference Include="..\Diagnostics\Diagnostics.csproj" />

然后,将以下行添加到 builder 声明下的 Program.cs 文件中:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddObservability("Products", builder.Configuration);

让我们将此代码添加到 eShopLite 应用中的“产品”服务