Mud.HttpUtils.OpenTelemetry 2.0.2

dotnet add package Mud.HttpUtils.OpenTelemetry --version 2.0.2
                    
NuGet\Install-Package Mud.HttpUtils.OpenTelemetry -Version 2.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Mud.HttpUtils.OpenTelemetry" Version="2.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Mud.HttpUtils.OpenTelemetry" Version="2.0.2" />
                    
Directory.Packages.props
<PackageReference Include="Mud.HttpUtils.OpenTelemetry" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Mud.HttpUtils.OpenTelemetry --version 2.0.2
                    
#r "nuget: Mud.HttpUtils.OpenTelemetry, 2.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Mud.HttpUtils.OpenTelemetry@2.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Mud.HttpUtils.OpenTelemetry&version=2.0.2
                    
Install as a Cake Addin
#tool nuget:?package=Mud.HttpUtils.OpenTelemetry&version=2.0.2
                    
Install as a Cake Tool

Mud.HttpUtils.OpenTelemetry

概述

Mud.HttpUtils.OpenTelemetry 是 Mud.HttpUtils 的 OpenTelemetry 适配包,提供 一键开启 Mud.HttpUtils 内置的分布式追踪(Tracing)与指标(Metrics)采集能力,并自动关联 .NET HttpClient 与 ASP.NET Core 的内置 Instrumentation。

目标框架

  • netstandard2.0
  • net6.0
  • net8.0
  • net10.0

安装

<PackageReference Include="Mud.HttpUtils.OpenTelemetry" Version="x.x.x" />

快速开始

1. ASP.NET Core 主机

var builder = WebApplication.CreateBuilder(args);

// 注册 Mud.HttpUtils 客户端(详见 Mud.HttpUtils.Client 文档)
builder.Services.AddMudHttpClient("myApi", c =>
{
    c.BaseAddress = new Uri("https://api.example.com");
});

// 一键开启 Mud.HttpUtils 的 OpenTelemetry 追踪与指标
builder.Services.AddMudHttpOpenTelemetry(options =>
{
    options.OtlpEndpoint = new Uri("http://otel-collector:4317");
});

var app = builder.Build();
app.Run();

2. 控制台应用

var services = new ServiceCollection();
services.AddLogging();
services.AddMudHttpClient("myApi", c => c.BaseAddress = new Uri("https://api.example.com"));
services.AddMudHttpOpenTelemetry();

using var provider = services.BuildServiceProvider();
// 使用 IHttpClientFactory 或 IEnhancedHttpClientFactory 发起请求

配置选项

MudHttpOpenTelemetryOptions

属性 类型 默认值 说明
EnableTracing bool true 是否启用分布式追踪
EnableMetrics bool true 是否启用指标采集
EnableLogging bool false 是否启用 OTLP 日志导出(向后兼容;依赖 .NET 8+ 的 ILogger 集成)
EnableHttpClientInstrumentation bool true 关联 .NET HttpClient 内置 ActivitySource
EnableAspNetCoreInstrumentation bool true 启用 ASP.NET Core 入站请求 Instrumentation(控制台应用无效)
OtlpEndpoint Uri? http://localhost:4317 OTLP 导出端点,null 表示不配置 OTLP 导出器
OtlpExportProtocol OtlpExportProtocol Grpc OTLP 导出协议(GrpcHttpProtobuf
UseShortExporterTimeout bool false 是否使用 5 秒短超时(开发调试用)
ServiceName string "Mud.HttpUtils.Application" OTel Resource 属性 service.name
ServiceVersion string MudHttpActivitySource.Version OTel Resource 属性 service.version
DeploymentEnvironment string "production" OTel Resource 属性 deployment.environment
SamplingRatio double 1.0 采样比率(0.0~1.0),生产环境建议 0.1~0.3。超出范围将在启动时抛出 ArgumentOutOfRangeException
ExportBatchSize int? null OTLP 每批导出最大条目数(映射到 BatchExportProcessorOptions.MaxExportBatchSize),null 使用 SDK 默认值(512)
ExportIntervalMilliseconds int? null OTLP 批量导出间隔毫秒数(映射到 BatchExportProcessorOptions.ScheduledDelayMilliseconds),null 使用 SDK 默认值(5000ms)
OtlpHeaders IDictionary<string, string>? null 自定义 OTLP Headers(如认证头)
ConfigureTracing Action<TracerProviderBuilder>? null 自定义追踪配置委托,在 Mud 默认配置之后执行
ConfigureMetrics Action<MeterProviderBuilder>? null 自定义指标配置委托,在 Mud 默认配置之后执行
ConfigureLogging Action<LoggerProviderBuilder>? null 自定义日志配置委托,在 Mud 默认配置之后执行

OtlpExportProtocol 枚举:本包自定义了 OtlpExportProtocolGrpc = 0HttpProtobuf = 1),用于覆盖 OpenTelemetry SDK 的同名类型。可通过 options.OtlpExportProtocol 指定导出协议。

批量导出配置范围ExportBatchSize / ExportIntervalMilliseconds 仅作用于 Tracing(Activity)的 BatchExportProcessorOptions,不影响 Metrics / Logs 的导出节奏。

EnableHttpClientInstrumentation:同时控制 Tracing 与 Metrics 两侧的 .NET HttpClient 关联(AddHttpClientInstrumentation),不仅关联 ActivitySource。

AddMudHttpOpenTelemetry 的两个重载均返回 OpenTelemetryBuilder,可继续链式追加配置;IConfiguration 重载的 sectionPath 参数默认值为 "MudHttpOpenTelemetry",可自定义绑定节点路径。

从 IConfiguration 绑定

除代码配置外,还支持从 appsettings.json 绑定选项:

builder.Services.AddMudHttpOpenTelemetry(builder.Configuration);

对应 appsettings.json

{
  "MudHttpOpenTelemetry": {
    "ServiceName": "my-service",
    "ServiceVersion": "1.0.0",
    "DeploymentEnvironment": "production",
    "SamplingRatio": 0.1,
    "EnableTracing": true,
    "EnableMetrics": true,
    "EnableLogging": false,
    "EnableHttpClientInstrumentation": true,
    "EnableAspNetCoreInstrumentation": true,
    "OtlpEndpoint": "http://otel-collector:4317",
    "OtlpExportProtocol": "Grpc",
    "ExportBatchSize": 256,
    "ExportIntervalMilliseconds": 5000,
    "OtlpHeaders": {
      "Authorization": "Bearer my-token"
    }
  }
}

也可同时使用配置绑定和代码配置:AddMudHttpOpenTelemetry(builder.Configuration, configure: options => { ... }),代码配置在配置绑定之后执行,可覆盖绑定值。

热更新限制:OpenTelemetry 配置在应用启动时一次性读取,不支持 IOptionsMonitor 热更新。这是因为 OpenTelemetry SDK 的 TracerProvider/MeterProvider 在构建后不可变。修改 appsettings.json 中的 MudHttpOpenTelemetry 节后需重启应用才能生效。如需运行时可变配置,请使用 AddMudHttpOpenTelemetry(Action<MudHttpOpenTelemetryOptions>?) 重载并在自定义委托中读取动态配置源。

高级配置示例

builder.Services.AddMudHttpOpenTelemetry(options =>
{
    options.OtlpEndpoint = new Uri("http://otel-collector:4318");
    options.OtlpExportProtocol = OtlpExportProtocol.HttpProtobuf;
    options.EnableAspNetCoreInstrumentation = false;

    // 追加自定义 ActivitySource
    options.ConfigureTracing = tp => tp.AddSource("MyApp.Business");

    // 追加 Prometheus 导出器(需额外引用 OpenTelemetry.Exporter.Prometheus.AspNetCore)
    options.ConfigureMetrics = mp => mp.AddPrometheusExporter();
});

自动采集的内容

追踪(Tracing)

ActivitySource 用途
Mud.HttpUtils.HttpClient Mud.HttpUtils 出站 HTTP 请求活动(含 method/url/status/duration)
System.Net.Http(.NET 内置) .NET HttpClient 底层 socket 活动
Microsoft.AspNetCore(.NET 内置) ASP.NET Core 入站请求活动

指标(Metrics)

Meter 指标 说明
Mud.HttpUtils.HttpClient mud.http.requests HTTP 请求计数
Mud.HttpUtils.HttpClient mud.http.request.duration HTTP 请求耗时直方图(ms)
Mud.HttpUtils.HttpClient mud.http.cache 缓存命中/未命中计数
Mud.HttpUtils.HttpClient mud.token.refresh 令牌刷新次数
Mud.HttpUtils.HttpClient mud.token.refresh.duration 令牌刷新耗时直方图(ms)
Mud.HttpUtils.HttpClient mud.http.retry 重试次数
Mud.HttpUtils.HttpClient mud.http.circuit_breaker.state 熔断器状态 Gauge
System.Net.Http(.NET 内置) http.client.* .NET HttpClient 内置指标

与健康检查配合

AddMudHttpOpenTelemetryAddMudHttpHealthChecks 可同时使用:

builder.Services.AddMudHttpClient("myApi", c => c.BaseAddress = new Uri("https://api.example.com"));
builder.Services.AddMudHttpHealthChecks();
builder.Services.AddMudHttpOpenTelemetry();

设计原则

  • 零侵入:用户代码无需任何改动,仅在 DI 注册时调用一次扩展方法
  • 可观测性零开销:无监听器时 ActivitySource.StartActivity 返回 nullCounter.Add 直接短路
  • 默认即生产可用:默认开启 Tracing + Metrics + OTLP gRPC 导出至本地 4317
  • 可扩展:通过 ConfigureTracing / ConfigureMetrics 委托追加自定义配置
  • AOT 兼容:所有 API 均为静态类型与委托,无反射

依赖项

版本 说明
Mud.HttpUtils.Abstractions 提供 MudHttpActivitySource / MudHttpMeter 静态源
OpenTelemetry 1.16.0 OpenTelemetry SDK 核心
OpenTelemetry.Extensions.Hosting 1.16.0 DI 集成扩展
OpenTelemetry.Exporter.OpenTelemetryProtocol 1.16.0 OTLP 导出器
OpenTelemetry.Instrumentation.Http 1.16.0 HttpClient Instrumentation
OpenTelemetry.Instrumentation.AspNetCore 1.16.0 ASP.NET Core Instrumentation

部署 OTLP 收集器

最简 Jaeger 部署(接收 OTLP gRPC 4317):

docker run -d --name jaeger \
  -p 16686:16686 \
  -p 4317:4317 \
  jaegertracing/all-in-one:1.62

启动应用后访问 http://localhost:16686 查看 Mud.HttpUtils 出站请求 span。

Prometheus + Grafana 抓取 Mud.HttpUtils.HttpClient Meter:

# otel-collector-config.yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
exporters:
  prometheus:
    endpoint: 0.0.0.0:8889
service:
  pipelines:
    metrics:
      receivers: [otlp]
      exporters: [prometheus]
    traces:
      receivers: [otlp]
      exporters: [otlp]  # 转发至 Jaeger
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.2 97 7/14/2026
2.0.1 95 7/13/2026
2.0.0 102 7/11/2026
2.0.0-rc5 101 7/8/2026