You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GCP GKE的Golang服务中过滤发送至Cloud Trace的Span?

解决Cloud Trace无关Span污染视图的方案

1. 本地自定义Span Processor过滤(代码层面)

既然你是直接用OpenTelemetry SDK把Span发送到Cloud Trace,不用Collector的话,最直接的方式是加个自定义Span Processor,在Span导出前把无关的过滤掉。

具体操作:

  • 实现一个Span Processor,在OnEnd方法里检查Span名称,要是属于你不想看到的那些(比如google.devtools.cloudtrace.v2.TraceService/BatchWriteSpans、google.pubsub.v1.Subscriber/StreamingPull这类),直接跳过导出逻辑。
  • 把这个过滤Processor套在Cloud Trace的导出Processor外面,加到TracerProvider里就行。

示例代码:

type filteringSpanProcessor struct {
    next          otel.SpanProcessor
    filteredNames map[string]struct{}
}

func NewFilteringProcessor(next otel.SpanProcessor) otel.SpanProcessor {
    return &filteringSpanProcessor{
        next: next,
        filteredNames: map[string]struct{}{
            "google.devtools.cloudtrace.v2.TraceService/BatchWriteSpans":    {},
            "google.pubsub.v1.Subscriber/StreamingPull":                   {},
            "google.devtools.cloudprofiler.v2.ProfilerService/CreateProfile": {},
            // 按需添加更多要过滤的Span名称
        },
    }
}

func (p *filteringSpanProcessor) OnStart(ctx context.Context, s sdktrace.ReadWriteSpan) {
    p.next.OnStart(ctx, s)
}

func (p *filteringSpanProcessor) OnEnd(s sdktrace.ReadOnlySpan) {
    // 命中过滤列表就跳过导出
    if _, exists := p.filteredNames[s.Name()]; exists {
        return
    }
    p.next.OnEnd(s)
}

func (p *filteringSpanProcessor) Shutdown(ctx context.Context) error {
    return p.next.Shutdown(ctx)
}

func (p *filteringSpanProcessor) ForceFlush(ctx context.Context) error {
    return p.next.ForceFlush(ctx)
}

初始化TracerProvider时用上这个Processor:

exporter, err := traceexporter.New(traceexporter.WithProjectID("你的项目ID"))
if err != nil {
    log.Fatal(err)
}

tp := sdktrace.NewTracerProvider(
    sdktrace.WithSpanProcessor(NewFilteringProcessor(sdktrace.NewBatchSpanProcessor(exporter))),
    // 其他原有配置...
)
otel.SetTracerProvider(tp)

2. Cloud Trace视图过滤(可视化层面)

不想改代码的话,直接在Trace Explorer里做自定义视图:

  • 打开Trace Explorer,点顶部的「视图」下拉框,选「创建视图」。
  • 加过滤规则,比如设置service.name不等于那些无关服务,或者直接指定只显示你的HTTP服务器服务名。
  • 保存后切换到这个视图,就只会看到你关心的Span了。

3. 关闭依赖库的自动追踪

那些无关Span大概率来自你项目里的GCP客户端库(比如Pub/Sub、Profiler的SDK),这些库默认会自动生成追踪Span。可以直接关闭对应库的自动追踪:

  • Pub/Sub客户端:可以设置环境变量GOOGLE_CLOUD_DISABLE_TRACING=true,或者初始化客户端时用NoopTracerProvider禁用追踪:
    client, err := pubsub.NewClient(ctx, "你的项目ID", option.WithGRPCDialOption(grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor(otelgrpc.WithTracerProvider(otel.NoopTracerProvider())))))
    
  • Cloud Profiler:如果不需要它的追踪,直接关闭相关自动配置就行。

内容的提问来源于stack exchange,提问作者guillaumelcv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 06:23:35