tracing

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package tracing 提供分布式链路追踪自动配置。

Package tracing 提供分布式追踪功能,用于 enhance 框架。

该模块提供 Span 创建、采样、导出和上下文传播等功能。 参考 OpenTelemetry 和 Spring Cloud Sleuth 的设计。

架构设计

  • Tracer: 追踪器,管理 Span 的创建、采样和导出
  • Span: 追踪单元,表示一个操作的完整生命周期
  • Sampler: 采样器接口,决定是否对请求进行采样
  • Exporter: 导出器接口,将 Span 数据导出到外部系统
  • SpanContext: 追踪上下文,用于跨服务传播
  • TraceHelper: 追踪助手,简化常见场景的追踪代码

核心功能

  • Span 创建: 支持父子关系和标签
  • 采样策略: 支持始终采样、从不采样和概率采样
  • 导出器: 支持控制台导出和自定义导出
  • 上下文传播: 支持 HTTP 头部注入和提取
  • Span 数量限制: 防止内存溢出
  • 并发安全: 使用读写锁和原子操作优化性能
  • 安全 ID 生成: 使用 crypto/rand 生成随机 ID

使用方式

创建追踪器:

tracer := tracing.NewTracer(
    tracing.WithServiceName("my-service"),
    tracing.WithSampler(tracing.NewProbabilitySampler(0.1)),
    tracing.WithExporter(&tracing.ConsoleExporter{}),
    tracing.WithMaxSpans(10000),
)

创建 Span:

span := tracer.StartSpan("HTTP GET", tracing.WithTags(map[string]string{
    "http.method": "GET",
    "http.url": "/api/users",
}))
defer span.End()

注入上下文:

headers := tracer.Inject(span.Context())

集成后端

具体实现位于 starter 子包:

  • starter/gin: Gin 框架集成
  • starter/fiber: Fiber 框架集成
  • starter/echo: Echo 框架集成
  • starter/chi: Chi 框架集成

Index

Constants

View Source
const (
	TracingEnabled = "tracing.enabled"
	ConditionTrue  = "true"
)

配置常量。

View Source
const (
	HeaderTraceID      = "X-Trace-Id"
	HeaderSpanID       = "X-Span-Id"
	HeaderParentSpanID = "X-Parent-Span-Id"
	HeaderSampled      = "X-Sampled"
)

HTTP 头部常量。

用于在 HTTP 请求间传播追踪上下文。 注意:使用 Go 的 http.CanonicalHeaderKey 格式(如 X-Trace-Id 而非 X-Trace-ID)

View Source
const (
	DefaultServiceName  = "enhance-app"
	DefaultMaxSpans     = 10000
	DefaultSamplingRate = 1.0
)

默认配置常量。

Variables

View Source
var (
	// ErrExporterNotSet 导出器未设置错误。
	ErrExporterNotSet = errors.New("exporter not set")

	// ErrInvalidSamplingRate 无效的采样率错误。
	ErrInvalidSamplingRate = errors.New("invalid sampling rate: must be between 0.0 and 1.0")
)

tracing 包错误定义。

Functions

func ContextWithSpan

func ContextWithSpan(ctx context.Context, span *Span) context.Context

ContextWithSpan 将 Span 上下文添加到 context。

返回新的 context,包含 Span 的追踪信息,可用于后续请求传播。

Types

type AlwaysOffSampler

type AlwaysOffSampler struct{}

AlwaysOffSampler 从不采样器。

func (*AlwaysOffSampler) ShouldSample

func (s *AlwaysOffSampler) ShouldSample() bool

ShouldSample 实现 Sampler 接口,始终返回 false。

type AlwaysOnSampler

type AlwaysOnSampler struct{}

AlwaysOnSampler 始终采样器。

func (*AlwaysOnSampler) ShouldSample

func (s *AlwaysOnSampler) ShouldSample() bool

ShouldSample 实现 Sampler 接口,始终返回 true。

type ConsoleExporter

type ConsoleExporter struct{}

ConsoleExporter 控制台导出器。

func (*ConsoleExporter) ExportSpans

func (e *ConsoleExporter) ExportSpans(spans []*Span) error

ExportSpans 实现 Exporter 接口,将 Span 打印到控制台。

type Exporter

type Exporter interface {
	// ExportSpans 导出 Span 列表。
	ExportSpans(spans []*Span) error
}

Exporter 导出器接口。

将 Span 数据导出到外部系统,如控制台、Jaeger、Zipkin 等。 实现此接口可自定义导出目标。

type ProbabilitySampler

type ProbabilitySampler struct {
	// contains filtered or unexported fields
}

ProbabilitySampler 概率采样器。

func NewProbabilitySampler

func NewProbabilitySampler(rate float64) *ProbabilitySampler

NewProbabilitySampler 创建概率采样器。

rate 参数范围 [0.0, 1.0],0.0 表示不采样,1.0 表示全量采样。

func (*ProbabilitySampler) ShouldSample

func (s *ProbabilitySampler) ShouldSample() bool

ShouldSample 实现 Sampler 接口,按概率返回是否采样。

type Sampler

type Sampler interface {
	// ShouldSample 返回是否应该采样。
	ShouldSample() bool
}

Sampler 采样器接口。

决定是否对请求进行采样。实现此接口可自定义采样策略。

内置实现

  • AlwaysOnSampler: 始终采样
  • AlwaysOffSampler: 从不采样
  • ProbabilitySampler: 概率采样

type Span

type Span struct {
	TraceID      TraceID           `json:"trace_id"`
	SpanID       SpanID            `json:"span_id"`
	ParentSpanID SpanID            `json:"parent_span_id,omitempty"`
	Name         string            `json:"name"`
	StartTime    time.Time         `json:"start_time"`
	EndTime      time.Time         `json:"end_time"`
	Status       SpanStatus        `json:"status"`
	Tags         map[string]string `json:"tags"`
	Events       []SpanEvent       `json:"events,omitempty"`
	Ended        bool              `json:"ended"`
	// contains filtered or unexported fields
}

Span 表示一个追踪单元,记录操作的开始和结束时间。

Span 是分布式链路追踪的基本单元,用于记录一个操作的完整生命周期。 每个 Span 包含 TraceID、SpanID、操作名称、状态、标签和事件等信息。

Span 是并发安全的,所有方法都通过互斥锁保护。

func (*Span) AddEvent

func (s *Span) AddEvent(name string, attrs ...map[string]string)

AddEvent 添加 Span 事件。

事件用于记录 Span 生命周期中的重要时间点,可附加属性。

func (*Span) Context

func (s *Span) Context() SpanContext

Context 获取 Span 追踪上下文。

返回的 SpanContext 可用于注入到 HTTP 请求头,实现跨服务追踪。

func (*Span) Duration

func (s *Span) Duration() time.Duration

Duration 获取 Span 持续时间。

如果 Span 未结束,返回从开始到当前的时间。

func (*Span) End

func (s *Span) End()

End 结束 Span。

记录 Span 的结束时间,计算持续时间。 如果 Span 已结束,此方法为幂等操作。

func (*Span) MarshalJSON

func (s *Span) MarshalJSON() ([]byte, error)

MarshalJSON 自定义 JSON 序列化。

添加 duration_ms 字段,表示 Span 持续时间(毫秒)。 该方法在锁内完成所有操作,避免递归锁定。

func (*Span) SetStatus

func (s *Span) SetStatus(status SpanStatus)

SetStatus 设置 Span 状态。

func (*Span) SetTag

func (s *Span) SetTag(key, value string)

SetTag 设置 Span 标签。

标签用于记录额外的元数据,如 HTTP 方法、URL、数据库操作等。

type SpanContext

type SpanContext struct {
	TraceID      TraceID `json:"trace_id"`
	SpanID       SpanID  `json:"span_id"`
	ParentSpanID SpanID  `json:"parent_span_id,omitempty"`
	Sampled      bool    `json:"sampled"`
}

SpanContext Span 追踪上下文。

包含追踪的核心信息,用于在 HTTP 请求间传播。

func TraceFromContext

func TraceFromContext(ctx context.Context) (SpanContext, bool)

TraceFromContext 从 context 获取追踪上下文。

如果 context 中包含 SpanContext,返回 true;否则返回空的 SpanContext 和 false。

type SpanEvent

type SpanEvent struct {
	Timestamp  time.Time         `json:"timestamp"`
	Name       string            `json:"name"`
	Attributes map[string]string `json:"attributes,omitempty"`
}

SpanEvent Span 事件。

记录 Span 生命周期中的重要时间点,可附加属性。

type SpanID

type SpanID string

SpanID Span ID 类型。

用于唯一标识一个 Span,同一链路中的每个 Span 有不同的 SpanID。

type SpanOption

type SpanOption func(*Span)

SpanOption Span 选项函数类型。

func WithContext

func WithContext(ctx SpanContext) SpanOption

WithContext 设置追踪上下文。

用于从外部恢复的 SpanContext 创建 Span。

func WithParent

func WithParent(parent *Span) SpanOption

WithParent 设置父 Span。

用于创建父子 Span 关系,子 Span 会继承父 Span 的 TraceID。

func WithTags

func WithTags(tags map[string]string) SpanOption

WithTags 设置标签。

批量设置 Span 标签,用于记录元数据。

type SpanStatus

type SpanStatus string

SpanStatus Span 状态枚举。

表示 Span 的执行结果状态。

const (
	StatusOK        SpanStatus = "OK"        // 成功
	StatusError     SpanStatus = "ERROR"     // 错误
	StatusCancelled SpanStatus = "CANCELLED" // 取消
)

Span 状态常量。

type TraceHelper

type TraceHelper struct {
	// contains filtered or unexported fields
}

TraceHelper 追踪助手。

提供便捷的追踪方法,简化常见场景的追踪代码。

func NewTraceHelper

func NewTraceHelper(tracer *Tracer) *TraceHelper

NewTraceHelper 创建追踪助手。

func (*TraceHelper) TraceDB

func (h *TraceHelper) TraceDB(operation, query string, fn func() error) error

TraceDB 追踪数据库操作。

自动创建 Span、记录数据库操作类型和 SQL 语句、处理错误状态。

func (*TraceHelper) TraceHTTP

func (h *TraceHelper) TraceHTTP(method, url string, fn func() error) error

TraceHTTP 追踪 HTTP 请求。

自动创建 Span、记录 HTTP 方法和 URL、处理错误状态。

func (*TraceHelper) TraceRPC

func (h *TraceHelper) TraceRPC(service, method string, fn func() error) error

TraceRPC 追踪 RPC 调用。

自动创建 Span、记录 RPC 服务和方法、处理错误状态。

type TraceID

type TraceID string

TraceID 追踪 ID 类型。

用于唯一标识一个完整的请求链路,跨多个服务保持不变。

type Tracer

type Tracer struct {
	// contains filtered or unexported fields
}

Tracer 追踪器结构。

管理 Span 的创建、采样和导出。 Tracer 是并发安全的,支持高并发场景下的 Span 创建。

func NewTracer

func NewTracer(opts ...TracerOption) *Tracer

NewTracer 创建追踪器。

使用函数式选项模式配置 Tracer,支持服务名称、采样器、导出器等配置。 默认使用 AlwaysOnSampler 和 ConsoleExporter。

func (*Tracer) Clear

func (t *Tracer) Clear()

Clear 清除所有 Span。

func (*Tracer) Export

func (t *Tracer) Export() error

Export 导出所有 Span。

使用导出器将当前所有 Span 导出到外部系统(如控制台、Jaeger 等)。 导出操作使用独立的锁,不阻塞 Span 创建。

func (*Tracer) Extract

func (t *Tracer) Extract(headers map[string]string) SpanContext

Extract 从 HTTP 头部提取追踪上下文。

从 HTTP 请求头中解析 TraceID、SpanID 等信息,恢复追踪上下文。

func (*Tracer) GetActiveSpanCount

func (t *Tracer) GetActiveSpanCount() int

GetActiveSpanCount 获取当前活跃的 Span 数量。

func (*Tracer) GetSpanCount

func (t *Tracer) GetSpanCount() int64

GetSpanCount 获取已创建的 Span 总数。

使用原子操作,无锁高效统计。

func (*Tracer) GetSpans

func (t *Tracer) GetSpans() []*Span

GetSpans 获取所有 Span 的副本。

返回的切片是内部切片的副本,修改不会影响 Tracer 内部状态。

func (*Tracer) Inject

func (t *Tracer) Inject(ctx SpanContext) map[string]string

Inject 注入追踪上下文到 HTTP 头部。

将 SpanContext 转换为 HTTP 头部键值对,用于跨服务传播追踪上下文。

func (*Tracer) StartSpan

func (t *Tracer) StartSpan(name string, opts ...SpanOption) *Span

StartSpan 创建新的 Span。

根据采样器决定是否创建真实 Span,未采样时返回空 Span。 支持通过 SpanOption 设置父 Span、标签等。

type TracerOption

type TracerOption func(*Tracer)

TracerOption 追踪器选项函数类型。

func WithExporter

func WithExporter(exporter Exporter) TracerOption

WithExporter 设置导出器。

func WithMaxSpans

func WithMaxSpans(max int) TracerOption

WithMaxSpans 设置最大 Span 数量限制(防止内存溢出)。

func WithSampler

func WithSampler(sampler Sampler) TracerOption

WithSampler 设置采样器。

func WithServiceName

func WithServiceName(name string) TracerOption

WithServiceName 设置服务名称。

type TracingAutoConfiguration

type TracingAutoConfiguration struct {
	// contains filtered or unexported fields
}

TracingAutoConfiguration 分布式链路追踪自动配置类。

当配置文件中启用 tracing 时(tracing.enabled=true)自动生效。 负责创建 tracing.Tracer 实例并注册到 IoC 容器中。 Web 框架(Gin/Fiber/Echo/Chi)会自动从容器获取 Tracer 并注册 tracing 中间件。

func (*TracingAutoConfiguration) Configure

Configure 配置分布式链路追踪。

func (*TracingAutoConfiguration) GetTracer

func (c *TracingAutoConfiguration) GetTracer() *Tracer

GetTracer 获取 Tracer 实例。

type TracingConfig

type TracingConfig struct {
	Enabled      bool    `json:"enabled" mapstructure:"enabled"`
	ServiceName  string  `json:"service_name" mapstructure:"service_name"`
	SamplingRate float64 `json:"sampling_rate" mapstructure:"sampling_rate"`
	MaxSpans     int     `json:"max_spans" mapstructure:"max_spans"`
}

TracingConfig 链路追踪配置。

Jump to

Keyboard shortcuts

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