tracing

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 5 Imported by: 0

README

tracing — 分布式链路追踪

提供 OpenTelemetry 风格的分布式链路追踪能力,支持 Span 生命周期管理、采样策略、批处理导出与 HTTP 中间件。

核心概念

概念 说明
Trace 一次完整请求的全链路追踪标识(TraceID)
Span 一次具体操作(如 DB 查询、HTTP 调用)的记录
Sampler 采样器,控制哪些 Trace 需要被记录
SpanProcessor Span 结束后的处理器(导出、聚合等)
SpanExporter 导出实现(控制台、Jaeger、Zipkin 等)

快速开始

import "github.com/leeforge/framework/tracing"

// 创建 Tracer
tracer, err := tracing.NewTracer(tracing.TracerConfig{
    ServiceName:    "user-service",
    ServiceVersion: "1.0.0",
    SamplingRate:   1.0, // 100% 采样
})

// 开始一个 Span
ctx, span := tracer.Start(ctx, "user.query")
defer tracer.End(span, err) // 传入 err 自动标记状态

// 添加属性
tracer.SetAttributes(span, map[string]interface{}{
    "user.id": userID,
    "db.table": "users",
})

// 添加事件
tracer.AddEvent(span, "cache.hit", map[string]interface{}{"key": cacheKey})

HTTP 追踪中间件

middleware := tracing.NewTracerMiddleware(tracer)

r := chi.NewRouter()
r.Use(middleware.Middleware)

中间件自动记录:http.methodhttp.urlhttp.hosthttp.status_code

高级用法

分布式追踪(DistributedTracer)
dt, err := tracing.NewDistributedTracer(tracing.DistributedTracingConfig{
    Enable:             true,
    ServiceName:        "cms-backend",
    SamplingRate:       0.1, // 10% 采样(生产推荐)
    EnableBatching:     true,
    BatchTimeout:       5 * time.Second,
    EnableDBTracing:    true,
    EnableCacheTracing: true,
    EnableHTTPTracing:  true,
})

// 追踪 DB 查询
err = dt.TraceDBQuery(ctx, "SELECT * FROM users WHERE id = $1", func(ctx context.Context) error {
    return db.QueryRow(ctx, id, &user)
})

// 追踪缓存操作
err = dt.TraceCacheOperation(ctx, "get", "user:123", func(ctx context.Context) error {
    return cache.Get(ctx, "user:123", &user)
})

// 追踪下游 HTTP 调用
err = dt.TraceHTTPCall(ctx, "GET", "https://api.service.com/data", func(ctx context.Context) error {
    return httpClient.Get(ctx, url)
})
批量处理(减少导出开销)
exporter := tracing.NewConsoleExporter()
processor := tracing.NewBatchSpanProcessor(exporter, 100, 5*time.Second)

tracer, _ := tracing.NewTracer(tracing.TracerConfig{
    ServiceName: "my-service",
    Processor:   processor,
})
从 Context 获取追踪信息
traceID := tracing.GetTraceID(ctx)
spanID := tracing.GetSpanID(ctx)
sampled := tracing.IsSampled(ctx)

采样策略

// 总是采样(开发/测试)
sampler := &tracing.AlwaysSampler{}

// 从不采样(禁用追踪)
sampler := &tracing.NeverSampler{}

// 按比例采样(生产推荐,如 10%)
sampler := tracing.NewTraceIDRatioBased(0.1)

SpanKind

类型 说明
SpanKindServer 接收请求的服务端
SpanKindClient 发出请求的客户端
SpanKindProducer 消息发布方
SpanKindConsumer 消息消费方
SpanKindInternal 内部操作(默认)

注意事项

  • 当前 ConsoleExporter 仅输出到 stdout,生产环境需实现 SpanExporter 接口对接 Jaeger/Zipkin
  • Span 的 End 方法必须调用,建议使用 defer tracer.End(span, err) 模式
  • 高流量场景务必配置合理的采样率(如 1%~10%),避免追踪数据淹没存储

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetSpanID

func GetSpanID(ctx context.Context) string

GetSpanID gets the span ID from context

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID gets the trace ID from context

func IsSampled

func IsSampled(ctx context.Context) bool

IsSampled checks if the span is sampled

Types

type AlwaysSampler

type AlwaysSampler struct{}

AlwaysSampler always samples

func (*AlwaysSampler) ShouldSample

func (a *AlwaysSampler) ShouldSample(traceID string) bool

type BatchSpanProcessor

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

BatchSpanProcessor processes spans in batches

func NewBatchSpanProcessor

func NewBatchSpanProcessor(exporter SpanExporter, batchSize int, timeout time.Duration) *BatchSpanProcessor

NewBatchSpanProcessor creates a new batch span processor

func (*BatchSpanProcessor) Flush

func (b *BatchSpanProcessor) Flush()

Flush flushes the current batch

func (*BatchSpanProcessor) OnEnd

func (b *BatchSpanProcessor) OnEnd(span *Span)

OnEnd processes a span when it ends

func (*BatchSpanProcessor) Shutdown

func (b *BatchSpanProcessor) Shutdown(ctx context.Context) error

Shutdown shuts down the processor

type ConsoleExporter

type ConsoleExporter struct{}

ConsoleExporter exports spans to the console

func NewConsoleExporter

func NewConsoleExporter() *ConsoleExporter

NewConsoleExporter creates a new console exporter

func (*ConsoleExporter) Export

func (c *ConsoleExporter) Export(span *Span) error

Export exports a span to the console

func (*ConsoleExporter) Shutdown

func (c *ConsoleExporter) Shutdown(ctx context.Context) error

Shutdown shuts down the exporter

type DistributedTracer

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

DistributedTracer represents a distributed tracer

func NewDistributedTracer

func NewDistributedTracer(config DistributedTracingConfig) (*DistributedTracer, error)

NewDistributedTracer creates a new distributed tracer

func (*DistributedTracer) GetFactory

func (d *DistributedTracer) GetFactory() *TracerFactory

GetFactory gets the factory

func (*DistributedTracer) GetTracer

func (d *DistributedTracer) GetTracer() *Tracer

GetTracer gets the tracer

func (*DistributedTracer) Shutdown

func (d *DistributedTracer) Shutdown(ctx context.Context) error

Shutdown shuts down the tracer

func (*DistributedTracer) TraceBusinessOperation

func (d *DistributedTracer) TraceBusinessOperation(ctx context.Context, name string, attrs map[string]interface{}, fn func(ctx context.Context) error) error

TraceBusinessOperation traces a business operation

func (*DistributedTracer) TraceCacheOperation

func (d *DistributedTracer) TraceCacheOperation(ctx context.Context, operation, key string, fn func(ctx context.Context) error) error

TraceCacheOperation traces a cache operation

func (*DistributedTracer) TraceDBQuery

func (d *DistributedTracer) TraceDBQuery(ctx context.Context, query string, fn func(ctx context.Context) error) error

TraceDBQuery traces a database query

func (*DistributedTracer) TraceHTTPCall

func (d *DistributedTracer) TraceHTTPCall(ctx context.Context, method, url string, fn func(ctx context.Context) error) error

TraceHTTPCall traces an HTTP call

type DistributedTracingConfig

type DistributedTracingConfig struct {
	Enable             bool
	ServiceName        string
	ServiceVersion     string
	SamplingRate       float64
	EnableBatching     bool
	BatchTimeout       time.Duration
	EnableMiddleware   bool
	EnableDBTracing    bool
	EnableCacheTracing bool
	EnableHTTPTracing  bool
}

DistributedTracingConfig represents the configuration for distributed tracing

func DefaultDistributedTracingConfig

func DefaultDistributedTracingConfig(serviceName string) DistributedTracingConfig

DefaultDistributedTracingConfig creates a default distributed tracing configuration

type NeverSampler

type NeverSampler struct{}

NeverSampler never samples

func (*NeverSampler) ShouldSample

func (n *NeverSampler) ShouldSample(traceID string) bool

type Sampler

type Sampler interface {
	ShouldSample(traceID string) bool
}

Sampler determines which spans to sample

type SimpleSpanProcessor

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

SimpleSpanProcessor is a simple span processor

func NewSimpleSpanProcessor

func NewSimpleSpanProcessor() *SimpleSpanProcessor

NewSimpleSpanProcessor creates a new simple span processor

func (*SimpleSpanProcessor) OnEnd

func (s *SimpleSpanProcessor) OnEnd(span *Span)

OnEnd processes a span when it ends

func (*SimpleSpanProcessor) Shutdown

func (s *SimpleSpanProcessor) Shutdown(ctx context.Context) error

Shutdown shuts down the processor

type Span

type Span struct {
	TraceID    string
	SpanID     string
	ParentID   string
	Name       string
	StartTime  time.Time
	EndTime    time.Time
	Attributes map[string]interface{}
	Events     []SpanEvent
	Status     SpanStatus
	Kind       SpanKind
}

Span represents a single operation within a trace

type SpanEvent

type SpanEvent struct {
	Time       time.Time
	Name       string
	Attributes map[string]interface{}
}

SpanEvent represents an event within a span

type SpanExporter

type SpanExporter interface {
	Export(span *Span) error
	Shutdown(ctx context.Context) error
}

SpanExporter exports spans

type SpanKind

type SpanKind int

SpanKind represents the kind of a span

const (
	SpanKindInternal SpanKind = 0
	SpanKindServer   SpanKind = 1
	SpanKindClient   SpanKind = 2
	SpanKindProducer SpanKind = 3
	SpanKindConsumer SpanKind = 4
)

type SpanProcessor

type SpanProcessor interface {
	OnEnd(span *Span)
	Shutdown(ctx context.Context) error
}

SpanProcessor processes spans

type SpanStartOption

type SpanStartOption func(*Span)

SpanStartOption represents a span start option

func WithAttributes

func WithAttributes(attrs map[string]interface{}) SpanStartOption

WithAttributes sets attributes

func WithParentID

func WithParentID(parentID string) SpanStartOption

WithParentID sets the parent span ID

func WithSpanKind

func WithSpanKind(kind SpanKind) SpanStartOption

WithSpanKind sets the span kind

type SpanStatus

type SpanStatus struct {
	Code    SpanStatusCode
	Message string
}

SpanStatus represents the status of a span

type SpanStatusCode

type SpanStatusCode int

SpanStatusCode represents the status code of a span

const (
	StatusCodeUnset SpanStatusCode = 0
	StatusCodeOK    SpanStatusCode = 1
	StatusCodeError SpanStatusCode = 2
)

type TraceIDRatioBased

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

TraceIDRatioBased samples based on a ratio

func NewTraceIDRatioBased

func NewTraceIDRatioBased(ratio float64) *TraceIDRatioBased

NewTraceIDRatioBased creates a new trace ID ratio based sampler

func (*TraceIDRatioBased) ShouldSample

func (t *TraceIDRatioBased) ShouldSample(traceID string) bool

type TracedOperation

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

TracedOperation represents a traced operation

func NewTracedOperation

func NewTracedOperation(tracer *Tracer, name string) *TracedOperation

NewTracedOperation creates a new traced operation

func (*TracedOperation) Execute

func (t *TracedOperation) Execute(ctx context.Context, fn func(ctx context.Context) error) error

Execute executes a function with tracing

func (*TracedOperation) ExecuteWithResult

func (t *TracedOperation) ExecuteWithResult(ctx context.Context, fn func(ctx context.Context) (interface{}, error)) (interface{}, error)

ExecuteWithResult executes a function with tracing and returns a result

type Tracer

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

Tracer represents a distributed tracing tracer

func NewTracer

func NewTracer(config TracerConfig) (*Tracer, error)

NewTracer creates a new tracer

func (*Tracer) AddEvent

func (t *Tracer) AddEvent(span *Span, name string, attrs map[string]interface{})

AddEvent adds an event to a span

func (*Tracer) End

func (t *Tracer) End(span *Span, err error)

End ends a span

func (*Tracer) SetAttributes

func (t *Tracer) SetAttributes(span *Span, attrs map[string]interface{})

SetAttributes sets attributes on a span

func (*Tracer) SetStatus

func (t *Tracer) SetStatus(span *Span, code SpanStatusCode, message string)

SetStatus sets the status of a span

func (*Tracer) Shutdown

func (t *Tracer) Shutdown(ctx context.Context) error

Shutdown shuts down the tracer

func (*Tracer) Start

func (t *Tracer) Start(ctx context.Context, name string, opts ...SpanStartOption) (context.Context, *Span)

Start starts a new span

type TracerConfig

type TracerConfig struct {
	ServiceName    string
	ServiceVersion string
	SamplingRate   float64
	Processor      SpanProcessor
}

TracerConfig represents the configuration for a tracer

func DefaultTracerConfig

func DefaultTracerConfig(serviceName string) TracerConfig

DefaultTracerConfig creates a default tracer configuration

type TracerFactory

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

TracerFactory creates and manages tracers

func NewTracerFactory

func NewTracerFactory() *TracerFactory

NewTracerFactory creates a new tracer factory

func (*TracerFactory) GetTracer

func (f *TracerFactory) GetTracer(serviceName string) (*Tracer, error)

GetTracer gets or creates a tracer

func (*TracerFactory) GetTracerWithConfig

func (f *TracerFactory) GetTracerWithConfig(config TracerConfig) (*Tracer, error)

GetTracerWithConfig gets a tracer with specific configuration

func (*TracerFactory) ShutdownAll

func (f *TracerFactory) ShutdownAll(ctx context.Context) error

ShutdownAll shuts down all tracers

type TracerMiddleware

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

TracerMiddleware is a middleware for HTTP tracing

func NewTracerMiddleware

func NewTracerMiddleware(tracer *Tracer) *TracerMiddleware

NewTracerMiddleware creates a new tracer middleware

func (*TracerMiddleware) Middleware

func (m *TracerMiddleware) Middleware(next http.Handler) http.Handler

Middleware wraps an HTTP handler with tracing

Jump to

Keyboard shortcuts

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