使用指标入门 - ASP.NET Core

了解如何在 ASP.NET Core 应用程序中使用 OpenTelemetry 指标

本指南将在几分钟内向您展示如何在 ASP.NET Core 应用程序中开始使用 OpenTelemetry .NET 指标。

先决条件

创建 ASP.NET Core 应用程序

创建一个新的 ASP.NET Core Web 应用程序

dotnet new web -o aspnetcoreapp
cd aspnetcoreapp

添加 OpenTelemetry 指标

安装所需的 OpenTelemetry 包

dotnet add package OpenTelemetry.Exporter.Console
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore

使用以下代码更新 Program.cs 文件

using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;

var builder = WebApplication.CreateBuilder(args);

// Configure OpenTelemetry with metrics and auto-start.
builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource
        .AddService(serviceName: builder.Environment.ApplicationName))
    .WithMetrics(metrics => metrics
        .AddAspNetCoreInstrumentation()
        .AddConsoleExporter((exporterOptions, metricReaderOptions) =>
        {
            metricReaderOptions.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds = 1000;
        }));

var app = builder.Build();

app.MapGet("/", () => $"Hello from OpenTelemetry Metrics!");

app.Run();

运行应用程序

运行应用程序

dotnet run

浏览到控制台中显示的 URL(例如,https://:5000)。

您应该会在控制台中看到类似以下的指标输出:

Export http.server.duration, Measures the duration of inbound HTTP requests., Unit: ms, Meter: OpenTelemetry.Instrumentation.AspNetCore/1.0.0.0
(2023-04-11T21:49:43.6915232Z, 2023-04-11T21:50:50.6564690Z) http.flavor: 1.1 http.method: GET http.route: / http.scheme: http http.status_code: 200 net.host.name: localhost net.host.port: 5000 Histogram
Value: Sum: 3.5967 Count: 11 Min: 0.073 Max: 2.5539
(-Infinity,0]:0
(0,5]:11
(5,10]:0
(10,25]:0
(25,50]:0
(50,75]:0
(75,100]:0
(100,250]:0
(250,500]:0
(500,750]:0
(750,1000]:0
(1000,2500]:0
(2500,5000]:0
(5000,7500]:0
(7500,10000]:0
(10000,+Infinity]:0

恭喜!您现在正在使用 OpenTelemetry 从 ASP.NET Core 应用程序收集指标。

工作原理

OpenTelemetry 注册

应用程序使用 ASP.NET Core 提供的依赖注入容器注册 OpenTelemetry 服务

builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource
        .AddService(serviceName: builder.Environment.ApplicationName))
    .WithMetrics(metrics => metrics
        .AddAspNetCoreInstrumentation()
        .AddConsoleExporter((exporterOptions, metricReaderOptions) =>
        {
            metricReaderOptions.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds = 1000;
        }));

此代码

  1. 使用 AddOpenTelemetry() 将 OpenTelemetry 添加到服务集合中
  2. 使用 ConfigureResource() 配置带有服务信息的资源
  3. 使用 WithMetrics() 设置指标收集
  4. 使用 AddAspNetCoreInstrumentation() 添加 ASP.NET Core 的自动仪表化
  5. 配置控制台导出器每秒导出一次指标

ASP.NET Core 仪表化

AddAspNetCoreInstrumentation() 方法会自动收集 HTTP 请求指标,包括:

  • 请求持续时间
  • HTTP 方法、路由和状态码
  • 网络信息

这些指标的收集无需在您的控制器或中间件中编写任何额外代码。

了解更多