Hyz.Trace 1.0.0

dotnet add package Hyz.Trace --version 1.0.0
                    
NuGet\Install-Package Hyz.Trace -Version 1.0.0
                    
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="Hyz.Trace" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hyz.Trace" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Hyz.Trace" />
                    
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 Hyz.Trace --version 1.0.0
                    
#r "nuget: Hyz.Trace, 1.0.0"
                    
#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 Hyz.Trace@1.0.0
                    
#: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=Hyz.Trace&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Hyz.Trace&version=1.0.0
                    
Install as a Cake Tool

Hyz.Trace

分布式链路追踪核心引擎,提供 TraceContext 上下文传播、TraceScope Span 管理、采样策略、性能熔断、敏感数据脱敏和 AOP 拦截支持。

目标框架

  • netstandard2.0 / net8.0 / net9.0 / net10.0

核心组件

TraceContext — 异步本地上下文

基于 AsyncLocal<T> 实现,随 ExecutionContext 自动跨 async/await 传播。

// 获取当前上下文
var ctx = TraceContext.Current;
string? traceId = TraceContext.TraceId;
string? spanId = TraceContext.SpanId;
bool isSuppressed = TraceContext.IsSuppressed;

// 快照与恢复(线程池/Task.Run 场景)
var snapshot = TraceContext.Capture();
await Task.Run(() => TraceContext.Run(snapshot, () => DoWork()));

// 抑制追踪(健康检查、后台任务等)
using (TraceContext.Suppress())
{
    await BackgroundTaskAsync();
}

TraceScope — Span 生命周期管理

using var scope = TraceScope.Create("OrderService.CreateOrder");
scope.SetTag("orderId", "ORD-12345");
scope.SetTag("customerId", "CUST-001");

try
{
    var order = await _repository.CreateAsync(...);
    scope.SetOk();
    return order;
}
catch (Exception ex)
{
    scope.SetError(ex);
    throw;
}

配置体系(TraceOptions)

支持三级配置优先级:环境变量 > JSON 配置 > 代码配置 > 默认值

// 通过 ASP.NET Core 链式 API 配置
builder.AddTrace(options =>
{
    // 基础开关
    options.Enabled = true;
    options.SampleRate = 1.0;

    // 性能保护
    options.MaxActiveSpans = 10000;
    options.MaxParameterDepth = 3;
    options.MaxSpanDataLength = 4096;
    options.CircuitBreakerThreshold = 0.1;   // 异常率超过 10% 触发熔断

    // 采样
    options.Sampler = new ProbabilisticSampler(0.5);  // 自定义采样器
    options.MaxSamplesPerSecond = 0;       // 0=不限制

    // 过滤
    options.IncludePatterns = new[] { "Order*", "Payment*" };
    options.ExcludePatterns = new[] { "HealthCheck*" };
    options.ExcludePathPrefixes = new[] { "/health", "/metrics" };
    options.SensitiveParameters = new[] { "password", "token" };

    // 上报配置
    options.DashboardServerAddress = "";      // 空=进程内模式
    options.DashboardApiKey = "";             // API Key(Dashboard 创建应用获取)
    options.DashboardProtocol = ReportProtocol.InProcess; // InProcess/Http/Grpc
    options.ReportBatchSize = 100;
    options.ReportBatchIntervalMs = 2000;
    options.ReportSendTimeoutSeconds = 10;
    options.ReportMaxRetries = 3;
    options.ReportMaxBufferSize = 10000;
});

TraceOptions 完整列表

属性 类型 默认值 说明
Enabled bool true 是否启用追踪
Sampler ISampler? null 自定义采样器实例
SampleRate double 1.0 采样率(0.0~1.0),1.0=全量
MaxActiveSpans int 10000 最大同时活跃 Span 数,超出自动丢弃
MaxParameterDepth int 3 参数序列化最大递归深度
MaxSpanDataLength int 4096 Span 数据(参数/返回值/标签)最大字符数
CircuitBreakerThreshold double 0.1 熔断阈值(错误率),超过则自动跳过追踪
CircuitBreakerCooldown TimeSpan 30s 熔断冷却时间
SensitiveParameters string[]? null 额外的敏感参数名列表(已内置 password/token/secret/creditcard 等)
SensitivePatterns string[]? null 敏感参数正则模式
IncludePatterns string[]? null 包含方法名通配符,仅匹配的方法才追踪
ExcludePatterns string[]? null 排除方法名通配符
ExcludePathPrefixes string[]? null 排除 HTTP 路径前缀(不创建 Span)
MaxSamplesPerSecond int 0 每秒最大采样数(0=不限制),超出降采样
DashboardServerAddress string "" Dashboard 服务端地址(空字符串=InProcess 模式)
DashboardApiKey string "" 上报 API Key(在 Dashboard 应用管理中获取,格式:trk_xxx...
DashboardProtocol ReportProtocol InProcess 上报协议:InProcess / Http / Grpc
ReportBatchSize int 100 批量上报最大 Span 数
ReportBatchIntervalMs int 2000 批量上报间隔(毫秒)
ReportSendTimeoutSeconds int 10 上报请求超时(秒)
ReportMaxRetries int 3 上报失败最大重试次数
ReportMaxBufferSize int 10000 内存缓冲区最大容量,超出丢弃旧数据

重要变更ApplicationName 配置项已移除。应用归属完全由 DashboardApiKey 确定,服务端通过 API Key 自动设置 ApplicationId 和 ApplicationName。

环境变量

所有 TraceOptions 属性均支持环境变量配置,前缀 HYZ_TRACE_,使用下划线代替驼峰命名:

环境变量 类型 说明
HYZ_TRACE_ENABLED bool 是否启用追踪
HYZ_TRACE_SAMPLE_RATE double 采样率(0.0~1.0)
HYZ_TRACE_MAX_ACTIVE_SPANS int 最大活跃 Span 数
HYZ_TRACE_MAX_PER_SECOND int 每秒最大采样数
HYZ_TRACE_DASHBOARD_SERVER string Dashboard 服务端地址
HYZ_TRACE_DASHBOARD_API_KEY string 上报 API Key
HYZ_TRACE_DASHBOARD_PROTOCOL enum 上报协议:InProcess/Http/Grpc
HYZ_TRACE_CIRCUIT_BREAKER_THRESHOLD double 熔断阈值
HYZ_TRACE_INCLUDE_PATTERNS string 包含模式(逗号分隔)
HYZ_TRACE_EXCLUDE_PATTERNS string 排除模式(逗号分隔)
HYZ_TRACE_EXCLUDE_PATH_PREFIXES string 排除路径前缀(逗号分隔)
HYZ_TRACE_SENSITIVE_PARAMETERS string 敏感参数(逗号分隔)

采样器

内置采样器

// 全量采样(默认)
var sampler = AlwaysOnSampler.Instance;

// 概率采样:50%
var sampler = new ProbabilisticSampler(0.5);

// 速率限制:每秒最多 100 个 Trace
var sampler = new RateLimitingSampler(100);

// 模式匹配采样(包含/排除通配符 + 下游采样器)
var sampler = new PatternSampler(
    new ProbabilisticSampler(0.5),
    includePatterns: new[] { "Order*", "Payment*" },
    excludePatterns: new[] { "HealthCheck*" });

自定义采样器

实现 ISampler 接口:

public interface ISampler
{
    bool ShouldSample(string methodName, Dictionary<string, string>? tags);
}

AOP 注册

DynamicProxy(推荐,接口代理)

// 注册单个带追踪的服务
builder.Services.AddTraced<IOrderService, OrderService>(ServiceLifetime.Scoped);

// 扫描程序集中所有标记了 [Trace] 的接口
builder.Services.AddTracedByType(typeof(OrderService).Assembly, ServiceLifetime.Scoped);

Fody IL 编织

安装 Hyz.Trace.Weaving.Fody 包,在任意类/方法上标记 [Trace] 特性:

[Trace]
public Order CreateOrder(string customerId, decimal amount) { ... }

Source Generator

使用 [Trace] 特性 + partial 方法:

public partial class OrderService
{
    [Trace]
    public partial Order CreateOrder(string customerId, decimal amount);
}

ITraceExporter 导出器

public interface ITraceExporter
{
    void Export(ISpanData span);
    Task ExportBatchAsync(IReadOnlyList<ISpanData> spans, CancellationToken ct = default);
}

内置导出器:

  • HttpTraceReporter(Hyz.Trace.Reporting.Http)— HTTP JSON 批量上报
  • GrpcTraceReporter(Hyz.Trace.Reporting.gRPC)— gRPC Protobuf 流式上报
  • DashboardExporter(Hyz.Trace.Dashboard)— 进程内直接写入存储
  • CompositeTraceExporter(Hyz.Trace.Storage.Abstractions)— 复合导出器(同时发往多个目标)

敏感数据脱敏

自动脱敏的参数名(大小写不敏感):

  • password, pwd, passwd
  • token, accesstoken, refreshtoken
  • secret, apikey, api_key, privatekey
  • creditcard, cardnumber, cvv
  • authorization, cookie

可通过 SensitiveParameters 追加自定义字段,或通过 SensitivePatterns 添加正则模式。

依赖包

  • Castle.Core — DynamicProxy AOP
  • Microsoft.Extensions.DependencyInjection.Abstractions — DI 抽象
  • Microsoft.Extensions.Logging.Abstractions — 日志抽象
  • Microsoft.Extensions.Options — 配置选项
  • Microsoft.Extensions.Http — HttpClient 工厂(上报器使用)
  • System.Text.Json — JSON 序列化

扩展包

包名 功能
Hyz.Trace.Client 客户端元包(核心+上报+ASP.NET+指标一站式安装)
Hyz.Trace.AspNet ASP.NET Core 中间件和 HttpClient 注入
Hyz.Trace.Reporting.Http HTTP 协议上报器
Hyz.Trace.Reporting.gRPC gRPC 协议上报器
Hyz.Trace.Dashboard Dashboard 中间件(进程内模式)
Hyz.Trace.Logging.Serilog Serilog 日志增强
Hyz.Trace.Logging.NLog NLog 布局渲染器
Hyz.Trace.Metrics.Prometheus Prometheus 指标
Hyz.Trace.Weaving.Fody Fody IL 编织插件
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  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 is compatible.  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 (5)

Showing the top 5 NuGet packages that depend on Hyz.Trace:

Package Downloads
Hyz.Trace.Client

Hyz.Trace 客户端全包 - .NET 应用内链路追踪 SDK,包含核心追踪、HTTP/gRPC 上报、ASP.NET Core 集成、Prometheus 指标、编译时分析器和源生成器。单个包即可使用全部功能。IL 编织能力请独立安装 Hyz.Trace.Weaving.Fody

Hyz.Trace.Logging.Serilog

Hyz.Trace - .NET 应用内链路追踪 SDK,支持分布式追踪、诊断与数据采集

Hyz.Trace.Logging.NLog

Hyz.Trace - .NET 应用内链路追踪 SDK,支持分布式追踪、诊断与数据采集

Hyz.Trace.Storage.Abstractions

Hyz.Trace - .NET 应用内链路追踪 SDK,支持分布式追踪、诊断与数据采集

Hyz.Trace.Dashboard

Hyz.Trace - .NET 应用内链路追踪 SDK,支持分布式追踪、诊断与数据采集

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 0 7/31/2026
0.9.0 0 7/31/2026
0.8.0 0 7/31/2026
0.7.0 46 7/31/2026
0.6.0 52 7/31/2026
0.5.0 120 7/30/2026
0.4.0 171 7/29/2026
0.3.0 370 7/28/2026