如何为AddOutgoingGoogleTraceHandler生成的链路追踪添加自定义标签?
解决方案
针对v4.3.0版本的Google.Cloud.Diagnostics.AspNetCore库,有两种兼容的方案可以为AddOutgoingGoogleTraceHandler生成的出站请求Span追加自定义标签:
方法1:自定义DelegatingHandler按需追加标签
该方案可以绑定HTTP请求/响应的上下文信息灵活加标签,是最常用的实现方式:
- 先定义自定义请求处理器
public class CustomOutgoingTraceTagHandler : DelegatingHandler { private readonly ITraceContextAccessor _traceContextAccessor; public CustomOutgoingTraceTagHandler(ITraceContextAccessor traceContextAccessor) { _traceContextAccessor = traceContextAccessor; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // 拿到Google追踪处理器生成的当前活跃Span if (_traceContextAccessor.TraceContext is ISpanContext currentSpan) { // 按需添加请求相关自定义标签 currentSpan.SetLabel("custom_request_domain", request.RequestUri?.Host ?? "unknown"); currentSpan.SetLabel("custom_request_method", request.Method.Method); } var response = await base.SendAsync(request, cancellationToken); // 也可以拿到响应后追加响应维度的标签 if (_traceContextAccessor.TraceContext is ISpanContext responseSpan) { responseSpan.SetLabel("custom_response_status", (int)response.StatusCode); } return response; } }
- 调整HTTP客户端的处理器注册顺序
// 注册自定义处理器的依赖 builder.Services.AddTransient<CustomOutgoingTraceTagHandler>(); // 注册HTTP客户端时,自定义处理器必须放在AddOutgoingGoogleTraceHandler之后 builder.Services.AddHttpClient("YourTargetHttpClient") .AddOutgoingGoogleTraceHandler() .AddHttpMessageHandler<CustomOutgoingTraceTagHandler>();
注意:处理器顺序不能颠倒,否则无法拿到对应请求生成的活跃Span
方法2:全局TraceProcessor统一批量加标签
如果需要给所有出站请求Span统一加固定规则的标签,不需要绑定单请求上下文,可以用该方案:
- 定义自定义Trace处理器
public class CustomOutgoingTraceProcessor : ITraceProcessor { public void Process(Trace trace) { // 筛选所有出站HTTP请求的Span,默认生成的Span名称前缀为HttpOutgoing foreach (var span in trace.Spans.Where(s => s.Name.StartsWith("HttpOutgoing"))) { // 统一追加全局自定义标签 span.Labels["custom_service_version"] = "v1.2.3"; span.Labels["custom_deploy_env"] = "production"; } } }
- 注册到全局追踪配置中
builder.Services.AddGoogleDiagnosticsForAspNetCore(options => { options.TraceOptions.TraceProcessors.Add(new CustomOutgoingTraceProcessor()); });
内容的提问来源于stack exchange,提问作者Gregordy
相关产品推荐
相关产品推荐

