trace

package
v1.57.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package trace 提供 OpenTelemetry 链路追踪集成(对标 Spring Cloud Sleuth): OTLP 导出 + 采样配置 + 便捷 Span 封装。接入后 HTTP 请求、日志自动携带 trace_id。

Index

Constants

This section is empty.

Variables

View Source
var ErrNotInitialized = errors.New("trace: call trace.Init first")

ErrNotInitialized 未调用 Init 时使用全局默认 Provider 的提示错误。

Functions

func Init

func Init(ctx context.Context, config Config) (func(context.Context) error, error)

Init 初始化 OpenTelemetry:设置全局 TracerProvider + 传播器。 返回关闭函数(应用退出时调用,刷出未导出的 Span)。 Endpoint 为空时仅初始化本地 Provider(不导出,Span 仍可编程使用)。

func Span

func Span(ctx context.Context, name string, fn func(ctx context.Context) error) error

Span 便捷封装:创建子 Span 并执行函数。 fn 返回 error 时 Span 标记 error 并记录异常;返回 span 结束时间(供耗时统计)。

err := trace.Span(ctx, "create-order", func(ctx context.Context) error {
    // 业务逻辑(内部再嵌套 Span 自动形成父子关系)
    return createOrder(ctx)
})

func SpanID

func SpanID(ctx context.Context) string

SpanID 当前 Span ID。

func TraceID

func TraceID(ctx context.Context) string

TraceID 从 Context 读取当前 Span 的 TraceID(日志关联用)。

func Tracer

func Tracer() trace.Tracer

Tracer 返回全局 Tracer(业务创建 Span 用)。

func WithAttribute

func WithAttribute(ctx context.Context, key string, value interface{})

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 链路追踪配置。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL