Go 后端 SDK 快速开始
让 Go 后端服务上报日志 + 自定义 metric + 分布式 trace span,并经 W3C traceparent 与端上
SDK 端到端贯通。v0 为纯 Argus 原生协议实现,零第三方依赖(仅标准库)。
对应 SDK:sdks/go-backend ·
示例:examples/go-backend-demo
安装
go get go.argusplatform.com/sdk/go-backendimport argus "go.argusplatform.com/sdk/go-backend"本模块是独立 go module(不在仓库根
go.work内)。本地构建 / 测试用GOWORK=off。
初始化 + 中间件
client, err := argus.New(argus.Config{
DSN: os.Getenv("ARGUS_DSN"), // argus://public:secret@host:port/project
ServiceName: "checkout-api",
Release: "v1.2.3",
SampleRate: 1, // trace 头部采样率 [0,1],0/缺省=全采;error span 始终保留
})
if err != nil {
panic(err)
}
defer client.Close() // flush 缓冲、停止后台定时器
mux := http.NewServeMux()
// ... 注册 handler ...
// Middleware:继承入站 traceparent → 创建 server span → 注入 ctx → 上报。
http.ListenAndServe(":8080", client.Middleware(mux))上报(日志 / metric / span)
mux.HandleFunc("/api/order", func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// 日志:自动带上本请求的 trace_id(中间件已把 active span 放进 ctx)。
client.Info(ctx, "order received", map[string]string{"user_id": "u-42"})
// metric:counter / gauge / histogram。
client.Counter("orders.placed", 1, map[string]string{"region": "us"})
// 手动子 span。
span, ctx := client.StartSpan(ctx, "charge-card")
span.SetAttribute("db.system", "postgres")
span.SetStatus("ok", "")
span.Finish()
w.WriteHeader(http.StatusOK)
})端到端 Trace:把链路传给下游
出站请求注入 traceparent,下游服务的 Argus SDK 会继承同一条 trace:
span, ctx := client.StartSpan(ctx, "call order-service")
defer span.Finish()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, downstreamURL, nil)
// ★ 关键:注入当前链路到出站请求头。
req.Header.Set("traceparent", argus.TraceparentFromContext(ctx))- 继承:
Middleware读入站traceparent,沿用其trace_id,以上游span_id为本 server span 的parent_span_id。无入站头则生成新 root trace。 - 采样一致:按
trace_id做 FNV-1a 一致性 hash(与 Web / Node SDK 同算法),整条 trace 要么 全采要么全弃;status=error的 span 强制保留。
详见 端到端 Trace 指南。
运行示例
cd examples/go-backend-demo
ARGUS_DSN='argus://demo-public:demo-secret@localhost:4318/demo' go run .
# 另开终端,模拟端上 SDK 带 traceparent 进来:
curl -H 'traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' \
http://localhost:8080/api/order然后在 Console /traces 页看到这条 trace:端上 span → 本服务 server span → 下游 client span,
外加一条带同 trace_id 的后端日志。
所有上报均为 best-effort:批量缓冲,满批 / 定时 / 手动 flush,上报失败丢弃,绝不影响业务 请求。