trace

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 17 Imported by: 0

README

trace 分布式链路追踪

基于 OpenTelemetry SDK 的薄封装:OTLP 导出全配置化(gRPC/HTTP 双协议),HTTP 服务端 span 中间件一行接入,trace id 自动桥接 X-Request-Id 日志约定——tracing 后端(Tempo/Jaeger/OTel Collector)的链路与本地日志聚合共用同一个 id,无需两套体系。

特性

  • OTLP 双协议:protocol: grpc|http 切换(默认 gRPC :4317,http :4318),兼容 Collector/Tempo/Jaeger 的两种接入形态
  • 配置化快速接入:内嵌业务配置结构体(四标签 + 默认值兜底),trace.NewBoot 经 app 的 Wire 一行接入(首位装配),span 中间件随装配自动注入
  • W3C 跨服务传递:标准 traceparent 头提取/注入,上游微服务的链路自动串联
  • 日志联动零改造:otel trace id(16 字节 32 位 hex)与 X-Request-Id 格式一致,注入后 middleware 的 TraceIDOf/TraceIDField 无感知生效
  • 生产友好:采样率可配(被丢弃的 span 仍产生有效 TraceID)、exporter 懒连接不可达不阻塞启动、Close 带超时刷盘且幂等、panic 场景 span 状态完整记录
  • 按需引入:otel 依赖仅在 import 本包时进入依赖树

快速开始

type Conf struct {
	app.Base
	Trace trace.Config `yaml:"trace"`
}

app.MustRun(&app.Boot[Conf]{
	Wire: func(c *Conf) []app.Component {
		return []app.Component{
			trace.NewBoot(c.Trace), // Wire 首位: 逆序释放时最后关闭, 在途 span 全量刷盘
			database.NewBoot(&c.Database),
		}
	},
})

span 中间件随装配自动注入并接管 X-Request-Id,server.trace_id 配置节无需再设置。不经 app.Boot 时手动接入:启动时 Init(cfg) + 路由挂载 Middleware(),退出前最后调用 Close()。

对应配置节(零配置可用,本地起一个 Jaeger all-in-one 或 OTel Collector 即可看到链路):

trace:
  service_name: tata       # 服务名(默认 basic-go), 后端按服务聚合
  protocol: grpc          # grpc(默认, 4317) | http(4318)
  endpoint: 127.0.0.1:4317 # collector 地址(默认按协议取本地端口)
  secure: false           # TLS(默认 false 明文; 生产务必开启或经代理终结)
  sample_ratio: 1.0       # 采样率 0.0~1.0(默认全量)
  headers: {}             # collector 鉴权头(grpc 仅建连发送, http 每请求携带)
  export_timeout: 5s      # 单次导出超时(默认 5s)
  shutdown_timeout: 5s    # Close 刷盘等待(默认 5s)

业务代码中创建子 span 与读取 trace id:

// handler 内创建子 span(自动挂到当前链路)
ctx, span := trace.Tracer("order").Start(c.Request.Context(), "create-order")
defer span.End()

// 日志聚合: 与既有 trace_id 约定一致, 无需改动
logger.Info("创建订单", middleware.TraceIDField(c))
logger.Info("手动取用", zap.String("trace_id", trace.TraceIDOf(c)))

接口总览

方法 说明
Init(cfg Config) error 初始化全局 TracerProvider:OTLP exporter + resource + 采样 + W3C 传播;重复调用需先 Close
Close() 带超时刷盘并关闭 provider(幂等);通常放 Close 钩子最后
Tracer(name) 全局 Tracer;未 Init 时为 noop,调用安全
Middleware() HTTP 服务端 span 中间件:提取 traceparent → 启动 server span → 桥接 X-Request-Id
TraceIDOf(c) 当前请求所属 span 的 trace id(32 位 hex),未启用时为空串
NewBoot(cfg) app Wire 组件适配器(boot.go):Init 初始化、Close 刷盘、Middlewares 贡献 span 中间件;Wire 放首位

span 语义

  • 命名:路由模板(c.FullPath,如 /api/v1/users/:id);未匹配路由(404)统一为 unknown,控制标签基数
  • 属性:http.method / http.route / http.target / http.status_code
  • 状态:状态码 ≥500 或 panic 时记 Error(panic 场景手动记 500 后重抛,交由 gin Recovery 兜底响应,span 数据不丢)
  • 采样:ParentBased(TraceIDRatioBased)——上游已采样则跟随,根 span 按 sample_ratio 抽样;被丢弃的 span 仍产生有效 TraceID,日志与跨服务传递不受影响

与 TraceID 中间件的关系

场景 行为
仅 trace_id: {} 日志聚合可用,无 span、无跨服务传递
仅 trace: 节 span + 跨服务传递 + 日志聚合(otel trace id 接管 X-Request-Id)
两者同时启用 trace 中间件后执行,覆盖前者写入的随机 id(同 key 注入),链路与日志仍一致;建议只启用 trace

注意事项

  • 依赖树:import 本包引入 otel SDK 与(gRPC 协议时)grpc-go;未 import 不进依赖树。本包依赖 ginx/middleware 桥接 trace id,会传递引入 gin/prometheus——ginx 用户无增量
  • collector 未就绪:exporter 懒连接,启动不阻塞;后台批量导出自动重试,失败仅 otel 内部日志,不影响请求
  • 鉴权头:gRPC 协议的 headers 仅在建连时发送;动态鉴权场景建议 protocol: http
  • 优雅降级:未调用 Init 直接使用 Middleware() 时为 noop provider,中间件无副作用

协同关系

  • ginx:Middlewares 字段注入 span 中间件;trace_id: {} 节可被本包替代
  • ginx/middleware:SetTraceID 桥接 TraceIDOf/TraceIDField 日志聚合约定
  • app:trace.NewBoot 经 Wire 一行接入(放首位),与 database/cache/cron 等组件同一接入模式

Documentation

Overview

Package trace 提供基于 OpenTelemetry 的分布式链路追踪: OTLP 导出配置化 (gRPC/HTTP 双协议)、HTTP 服务端 span 中间件与 trace_id 日志联动。

初始化即接入——app.Boot 场景经 Wire 一行(放首位: 组件逆序释放时 trace 最后关闭, 其余资源关停产生的在途 span 得以全量刷盘), span 中间件随装配 自动注入并接管 X-Request-Id, server.trace_id 配置节无需再设置:

type Conf struct {
	app.Base
	Trace trace.Config `yaml:"trace"`
}

app.MustRun(&app.Boot[Conf]{
	Wire: func(c *Conf) []app.Component {
		return []app.Component{
			trace.NewBoot(c.Trace), // Wire 首位
			database.NewBoot(&c.Database),
		}
	},
})

对应 yaml 配置节:

trace:
  service_name: tata   # 服务名(默认 basic-go), tracing 后端按服务聚合
  protocol: grpc       # OTLP 导出协议 grpc(默认, 4317)/http(4318)
  endpoint: 127.0.0.1:4317 # collector 地址(默认按协议取本地端口)
  secure: false        # 默认明文连接; 生产开启 TLS 或经代理终结

span 经 W3C traceparent 头跨服务传递, trace id(32 位 hex)自动桥接 X-Request-Id 约定, middleware.TraceIDOf/TraceIDField 照常可用。

本包依赖 OpenTelemetry SDK 与 gin; 未 import 本包时 otel 依赖不进依赖树。 独立使用(不经 app.Boot)时手动调用: 启动时 Init(cfg) + 路由挂载 Middleware(), 退出前最后调用 Close()。

Index

Constants

View Source
const (
	// ProtocolGRPC OTLP over gRPC, 默认协议
	ProtocolGRPC = "grpc"
	// ProtocolHTTP OTLP over HTTP(Protobuf 载荷)
	ProtocolHTTP = "http"
)

OTLP 导出协议与默认约定

Variables

This section is empty.

Functions

func Close

func Close()

Close 刷盘并关闭全局 TracerProvider: 等待在途 span 导出完成(至多 ShutdownTimeout)。 通常在 app.Boot 的 Close 钩子中最后调用(其余资源释放之后, 在途 span 全量导出)。 幂等: 未初始化时为空操作, 重复调用安全。

func Init

func Init(cfg Config) error

Init 初始化全局 TracerProvider 并注册 W3C 传播协议(TraceContext + Baggage)。 exporter 懒连接: collector 暂不可达不影响启动, 后台批量导出自动重试。 通常在 app.Boot 的 Init 钩子中调用; 重复调用需先 Close, 否则返回错误。

func Middleware

func Middleware() gin.HandlerFunc

Middleware 构建链路追踪中间件, 经 ginx.Gin.Middlewares(或原生 gin Use)注入:

提取 W3C traceparent(跨服务串联上游) -> 按路由模板启动 server span
-> 桥接 X-Request-Id 约定 -> c.Next

span 上下文经 c.Request.WithContext 回写, handler 侧无感知, 后续创建的 子 span 与 Tracer 调用均挂到当前链路。otel trace id 为 16 字节 32 位 hex, 与 X-Request-Id 约定格式一致: 注入 gin context 后 middleware.TraceIDOf / TraceIDField 照常可用, 日志聚合复用既有约定; 与 TraceID 中间件同时启用时, 本中间件后执行并覆盖其写入的随机 id(建议只启用其一)。

未调用 Init 时全局 provider 为 noop, span 上下文无效, 本中间件优雅降级为无副作用。

func TraceIDOf

func TraceIDOf(c *gin.Context) string

TraceIDOf 读取当前请求所属 span 的 trace id(32 位 hex); 未启用 trace 中间件时返回空串。 被采样丢弃的 span 上下文仍有效, 返回值照常非空。

func Tracer

func Tracer(name string) oteltrace.Tracer

Tracer 返回指定名称的全局 Tracer; 未 Init 时为 noop 实现, 调用安全。

Types

type Boot

type Boot struct {
	// Config 链路追踪配置
	Config Config
}

Boot 组件适配器: 一行接入 app.Boot 的 Wire 装配钩子(结构化匹配 app.Component 与 app.Middlewarer 约定, 无需 import app)。

装配位置约定: Wire 列表中放首位——组件逆序释放时 trace 最后关闭, 其余资源关停操作产生的在途 span 得以全量刷盘(与 Close 的"最后调用"约定一致)。 span 中间件接管 X-Request-Id 约定, server.trace_id 配置节无需再设置。

func NewBoot

func NewBoot(cfg Config) *Boot

NewBoot 构建链路追踪组件适配器: Init 初始化全局 TracerProvider, Middlewares 贡献 HTTP 服务端 span 中间件, Close 刷盘并释放。

trace.NewBoot(c.Trace) // OTLP 导出 + span 中间件 + 关停刷盘, 一行接入

func (*Boot) Close

func (b *Boot) Close()

Close 刷盘在途 span 并关闭全局 TracerProvider(幂等)。

func (*Boot) Init

func (b *Boot) Init() error

Init 初始化全局 TracerProvider 并注册 W3C 传播协议。

func (*Boot) Middlewares

func (b *Boot) Middlewares() []gin.HandlerFunc

Middlewares 贡献 HTTP 服务端 span 中间件, 由装配方在路由构建前注入引擎。

func (*Boot) Name

func (b *Boot) Name() string

Name 组件名, 用于启动失败错误与关停日志标识。

type Config

type Config struct {
	// ServiceName 服务名, 作为 span 的资源标识(service.name 属性),
	// 同一服务的所有实例应保持一致, 在 tracing 后端按服务聚合
	ServiceName string `yaml:"service_name" toml:"service_name" json:"service_name" mapstructure:"service_name"`

	// Protocol OTLP 导出协议: "grpc"(默认) | "http", 非法值归一为 grpc
	Protocol string `yaml:"protocol" toml:"protocol" json:"protocol" mapstructure:"protocol"`

	// Endpoint collector 地址(host:port); 未设置时按协议取默认端口
	// (grpc 127.0.0.1:4317, http 127.0.0.1:4318)
	Endpoint string `yaml:"endpoint" toml:"endpoint" json:"endpoint" mapstructure:"endpoint"`

	// Secure 是否使用 TLS 加密连接 collector: 默认 false 明文连接,
	// 面向本地/内网 collector 的快速接入; 生产环境务必开启,
	// 或经由 sidecar/网关终结 TLS 后再对接
	Secure bool `yaml:"secure" toml:"secure" json:"secure" mapstructure:"secure"`

	// SampleRatio 采样率, 取值 0.0~1.0(默认 1.0 全量); 非法值回退全量。
	// 被采样丢弃的 span 仍产生有效 TraceID, 日志聚合与跨服务传递不受影响
	SampleRatio float64 `yaml:"sample_ratio" toml:"sample_ratio" json:"sample_ratio" mapstructure:"sample_ratio"`

	// Headers OTLP 导出的附加请求头(如 collector 鉴权凭证);
	// 注意 grpc 仅在建连时发送, http 每次请求携带, 鉴权场景建议 http 协议
	Headers map[string]string `yaml:"headers" toml:"headers" json:"headers" mapstructure:"headers"`

	// ExportTimeout 单次导出的超时时间(默认 5s)
	ExportTimeout time.Duration `yaml:"export_timeout" toml:"export_timeout" json:"export_timeout" mapstructure:"export_timeout"`

	// ShutdownTimeout Close 时等待在途 span 刷盘的最大时长(默认 5s)
	ShutdownTimeout time.Duration `yaml:"shutdown_timeout" toml:"shutdown_timeout" json:"shutdown_timeout" mapstructure:"shutdown_timeout"`
}

Config 链路追踪配置, 内嵌到业务配置结构体后经 app.Boot 加载, 或独立使用时直接构造字面量; 未设置(零值)时 applyDefaults 兜底。

Jump to

Keyboard shortcuts

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