Documentation
¶
Overview ¶
Package trace 提供 OpenTelemetry 链路追踪集成(对标 Spring Cloud Sleuth): OTLP 导出 + 采样配置 + 便捷 Span 封装。接入后 HTTP 请求、日志自动携带 trace_id。
Index ¶
- Variables
- func Init(ctx context.Context, config Config) (func(context.Context) error, error)
- func Span(ctx context.Context, name string, fn func(ctx context.Context) error) error
- func SpanID(ctx context.Context) string
- func TraceID(ctx context.Context) string
- func Tracer() trace.Tracer
- func WithAttribute(ctx context.Context, key string, value interface{})
- type Config
Constants ¶
This section is empty.
Variables ¶
View Source
var ErrNotInitialized = errors.New("trace: call trace.Init first")
ErrNotInitialized 未调用 Init 时使用全局默认 Provider 的提示错误。
Functions ¶
func Init ¶
Init 初始化 OpenTelemetry:设置全局 TracerProvider + 传播器。 返回关闭函数(应用退出时调用,刷出未导出的 Span)。 Endpoint 为空时仅初始化本地 Provider(不导出,Span 仍可编程使用)。
func Span ¶
Span 便捷封装:创建子 Span 并执行函数。 fn 返回 error 时 Span 标记 error 并记录异常;返回 span 结束时间(供耗时统计)。
err := trace.Span(ctx, "create-order", func(ctx context.Context) error {
// 业务逻辑(内部再嵌套 Span 自动形成父子关系)
return createOrder(ctx)
})
func WithAttribute ¶
WithAttribute 向当前 Span 追加属性(函数内多次调用)。
Types ¶
type Config ¶
type Config struct {
// ServiceName 服务名(上报到 Jaeger/OTel Collector 的 service.name)。
ServiceName string
// Endpoint OTLP HTTP 采集端点(如 http://127.0.0.1:4318);空时不启用导出。
Endpoint string
// Environment 环境(dev/test/prod,写入 resource 属性)。
Environment string
// SampleRatio 采样率 0-1(默认 1:全量;生产建议 0.1-0.3)。
SampleRatio float64
// Timeout 导出超时(默认 5s)。
Timeout time.Duration
}
Config 链路追踪配置。
Click to show internal directories.
Click to hide internal directories.