Go + PostgreSQL + Valkey backend (cmd/internal/migrations), uni-app mobile frontend, PC web (web/), admin console (admin/), Android WebView container (android_project/). Build artifacts, node_modules, local env and debug screenshots excluded.
88 lines
2.7 KiB
Go
88 lines
2.7 KiB
Go
package telemetry
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"time"
|
||
|
||
"go.opentelemetry.io/otel"
|
||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
|
||
"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
|
||
"go.opentelemetry.io/otel/propagation"
|
||
"go.opentelemetry.io/otel/sdk/resource"
|
||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
|
||
)
|
||
|
||
// Config 决定追踪怎么导出。
|
||
type Config struct {
|
||
ServiceName string
|
||
Env string
|
||
// OTLPEndpoint 为空时用 stdout 导出(本地开发),
|
||
// 生产环境指向 Jaeger/Tempo 的 OTLP gRPC 端点,如 "otel-collector:4317"
|
||
OTLPEndpoint string
|
||
// SampleRatio 采样率。1.0 全采(开发),0.1 采 10%(生产高流量)
|
||
SampleRatio float64
|
||
}
|
||
|
||
// InitTracer 初始化 OpenTelemetry 追踪,返回 shutdown 函数。
|
||
//
|
||
// 为什么需要它:日志能查到单个请求耗时,但查不到「这 142ms 花在
|
||
// PG 查询、Valkey 往返还是通知写入上」。追踪把一次请求拆成 span 树,
|
||
// 直接看出瓶颈在哪一段。
|
||
func InitTracer(ctx context.Context, cfg Config) (func(context.Context) error, error) {
|
||
var exporter sdktrace.SpanExporter
|
||
var err error
|
||
|
||
if cfg.OTLPEndpoint == "" {
|
||
// 本地开发:打到 stdout,肉眼可见,不依赖外部服务
|
||
exporter, err = stdouttrace.New(stdouttrace.WithPrettyPrint())
|
||
} else {
|
||
exporter, err = otlptracegrpc.New(ctx,
|
||
otlptracegrpc.WithEndpoint(cfg.OTLPEndpoint),
|
||
otlptracegrpc.WithInsecure(), // 内网 collector 不启 TLS;跨公网必须开
|
||
otlptracegrpc.WithTimeout(5*time.Second),
|
||
)
|
||
}
|
||
if err != nil {
|
||
return nil, fmt.Errorf("创建 trace exporter 失败: %w", err)
|
||
}
|
||
|
||
res, err := resource.New(ctx,
|
||
resource.WithAttributes(
|
||
semconv.ServiceName(cfg.ServiceName),
|
||
semconv.DeploymentEnvironment(cfg.Env),
|
||
),
|
||
resource.WithHost(),
|
||
resource.WithProcessRuntimeDescription(),
|
||
)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("创建 resource 失败: %w", err)
|
||
}
|
||
|
||
ratio := cfg.SampleRatio
|
||
if ratio <= 0 || ratio > 1 {
|
||
ratio = 1.0
|
||
}
|
||
|
||
tp := sdktrace.NewTracerProvider(
|
||
sdktrace.WithBatcher(exporter,
|
||
// 批量导出:单条上报会给 collector 造成巨大压力
|
||
sdktrace.WithMaxQueueSize(4096),
|
||
sdktrace.WithBatchTimeout(2*time.Second),
|
||
),
|
||
sdktrace.WithResource(res),
|
||
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratio))),
|
||
)
|
||
|
||
otel.SetTracerProvider(tp)
|
||
// W3C TraceContext 是跨服务传播的标准;
|
||
// 美篇用的 X-B3-* 是 Zipkin 时代的老格式,新项目一律用 W3C
|
||
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
||
propagation.TraceContext{},
|
||
propagation.Baggage{},
|
||
))
|
||
|
||
return tp.Shutdown, nil
|
||
}
|