Hyz.Trace 1.4.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Hyz.Trace --version 1.4.0
                    
NuGet\Install-Package Hyz.Trace -Version 1.4.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.4.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hyz.Trace" Version="1.4.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.4.0
                    
#r "nuget: Hyz.Trace, 1.4.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.4.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.4.0
                    
Install as a Cake Addin
#tool nuget:?package=Hyz.Trace&version=1.4.0
                    
Install as a Cake Tool

Hyz.Trace

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

核心能力

  • 上下文传播 — 基于 AsyncLocal<T>TraceContext,随 ExecutionContextasync/await 自动传播
  • Span 生命周期管理TraceScope 统一创建/结束 Span,支持标签、错误记录与父子关系
  • 采样与熔断 — 概率/速率/模式采样器,异常率超阈值自动熔断
  • 敏感数据脱敏 — 内置密码、Token、密钥等字段自动脱敏
  • AOP 拦截 — DynamicProxy / Fody IL 编织 / Source Generator 三种织入方式
  • 双层缓冲上报TraceScope 有界 Channel 导出 + 上报器无界缓冲后台刷新
  • 丢弃可观测(OnDrop) — 缓冲满丢弃 Span 时触发回调事件,便于日志与监控定位(见「丢弃回调」)
  • 优雅停机兜底TraceScope.Shutdown() 兜底排空缓冲,避免进程退出丢数据(见「优雅停机兜底」)

目标框架

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

    // 诊断日志(排查时开启,生产环境建议关闭)
    options.EnableDiagnosticLogging = false;
});

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 内存缓冲区最大容量,超出丢弃旧数据
EnableDiagnosticLogging bool false 诊断日志开关,开启后 Create/Dispose/Export 路径输出详细 Trace 日志

重要变更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 敏感参数(逗号分隔)
HYZ_TRACE_DIAGNOSTIC_LOGGING bool 诊断日志开关(true/false)

采样器

内置采样器

// 全量采样(默认)
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)— 复合导出器(同时发往多个目标)

所有上报器均实现 ITraceReporter(继承 ITraceExporter),并在 Span 因缓冲满被丢弃时触发 OnDrop 事件(见下文「丢弃回调」)。

丢弃回调(OnDrop)

当 Span 因缓冲达到上限无法入队而被丢弃时(导出通道满 Source="ExportChannel",或上报器缓冲满 Source="HttpReporter"/"GrpcReporter"),会触发 OnDrop 事件,便于日志与监控定位丢失的数据

// 全局级别:覆盖所有 reporter 及导出通道的丢弃
TraceScope.OnDrop += info =>
    _logger.Warning("Span dropped: {Source} {Method} {Reason} (buffer={BufferCount})",
        info.Source, info.MethodName, info.Reason, info.BufferCount);

// 单 reporter 级别(仅该上报器的缓冲丢弃)
reporter.OnDrop += info => Console.WriteLine(info.ToString());

TraceDroppedInfo 字段:

字段 类型 说明
TraceId string? 被丢弃 Span 的 TraceId(若已知)
SpanId string? 被丢弃 Span 的 SpanId(若已知)
MethodName string? 所属方法名(若已知)
Source string? 丢弃位置:ExportChannel / HttpReporter / GrpcReporter
Reason string? 丢弃原因,如 "reporter buffer full (max=10000, current=10001)"
BufferCount int 丢弃时缓冲中尚未上报的 Span 数量(近似)
TimestampUtc DateTime 丢弃发生时间(UTC)

提示TraceScope.DroppedCount 提供累计丢弃计数(仅导出通道侧),可结合 OnDrop 一起用于健康检查与告警。

优雅停机兜底(Shutdown)

进程退出前应调用 TraceScope.Shutdown(),它会关闭导出通道、取消后台消费者,并依次调用每个已注册 reporter 的 FlushAsync 兜底排空,避免缓冲中尚未发送的 Span 随进程退出而丢失:

// 在 Program.cs 中注册进程退出钩子
AppDomain.CurrentDomain.ProcessExit += (_, _) => TraceScope.Shutdown();

// 调整兜底刷新超时(默认 10000ms,超时则放弃等待)
TraceScope.ShutdownFlushTimeoutMs = 10000;
TraceScope.Shutdown();   // 阻塞直至各 reporter 刷新完成或超时

若使用 IHostedService / IHostApplicationLifetime,可在 StopAsync 中调用 TraceScope.Shutdown()。Shutdown 后仍可再次 AddReporter 重建通道(便于测试隔离与优雅重启)。

敏感数据脱敏

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

  • 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.Storage.Abstractions

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

Hyz.Trace.Client

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

Hyz.Trace.Logging.NLog

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

Hyz.Trace.Logging.Serilog

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.4.1 268 8/12/2026
1.4.0 272 8/11/2026
1.3.9 255 8/11/2026
1.3.8 272 8/10/2026
1.3.7 269 8/7/2026
1.3.6 265 8/7/2026
1.3.5 261 8/7/2026
1.3.4 259 8/7/2026
1.3.3 275 8/7/2026
1.3.2 271 8/6/2026
1.3.1 302 8/6/2026
1.3.0 302 8/4/2026
1.2.7 310 8/3/2026
1.2.6 330 8/2/2026
1.2.5 314 8/2/2026
1.2.4 299 8/2/2026
1.2.3 311 8/2/2026
1.2.2 311 8/1/2026
1.2.1 296 8/1/2026
1.2.0 323 8/1/2026
Loading failed