x/net/trace 不适合现代 Go 应用的请求追踪,因其早已弃用、无分布式上下文传播能力、不支持 trace ID 生成与跨 goroutine 传递、无 context.Context 集成、不兼容 OpenTelemetry 标准且数据仅存内存。

x/net/trace 不适合现代 Go 应用的请求追踪,它早已被弃用,且不具备分布式上下文传播能力。
为什么 x/net/trace 不能用于真实请求追踪
这个包是 Go 早期(2014–2016)为调试 HTTP 服务内部状态设计的简易工具,本质是运行时内存中的一组可 HTTP 访问的调试页面(如 /debug/requests),不支持 trace ID 生成、跨 goroutine 传递、采样控制或后端导出。
- 所有 trace 数据只存在内存里,进程重启即丢失
- 没有
context.Context集成,无法串联 HTTP handler → DB query → RPC 调用 - 不兼容 OpenTracing / OpenTelemetry 标准,无法对接 Jaeger、Zipkin 或 OTLP 后端
- Go 1.16+ 中已明确标记为 deprecated,
go.dev文档首页直接提示 “This package is no longer actively maintained”
替代方案:用 otelhttp + otelsql 做真实请求追踪
如果你需要的是生产级请求追踪(比如查看一次 HTTP 请求经过了哪些服务、耗时分布、SQL 执行详情),应使用 OpenTelemetry Go SDK。
- HTTP 层:用
otelhttp.NewHandler包裹 handler,自动注入 trace ID 并记录 status、method、path - 数据库层:用
otelsql.Register包裹sql.Open,自动捕获 query、args、duration - 手动 span:在关键逻辑处调用
tracer.Start(ctx, "do-something"),并确保传入带 trace 的ctx - 导出器:选
otlphttp(推送到 OTEL Collector)或zipkin(直连 Zipkin)
示例片段:
import (
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel/exporters/zipkin"
"go.opentelemetry.io/otel/sdk/trace"
)
exp, _ := zipkin.New("http://localhost:9411/api/v2/spans")
tp := trace.NewTracerProvider(trace.WithBatcher(exp))
otel.SetTracerProvider(tp)
http.Handle("/api/", otelhttp.NewHandler(http.HandlerFunc(handler), "api"))
如果只是想快速看当前 goroutine 的执行栈和活跃 trace —— 用 net/http/pprof 更合适
x/net/trace 的原始用途(查看当前活跃 HTTP 请求列表)现在完全由 net/http/pprof 覆盖,且更稳定、更标准。
- 启动时注册:
http.HandleFunc("/debug/pprof/", pprof.Index) - 访问
/debug/pprof/goroutine?debug=2可看到带栈的活跃 goroutine -
/debug/pprof/trace可采集 5 秒运行时 trace(含调度、GC、阻塞事件),用go tool trace分析 - 无需额外依赖,Go 标准库自带,无维护风险
真正做请求追踪时,最大的遗漏点不是选错函数,而是忘了把 trace context 从入站请求透传到所有下游调用(包括 HTTP header、gRPC metadata、消息队列的 headers)。一旦断链,span 就变成孤立节点——这比不用 tracing 还误导人。

















