Node 后端 SDK 快速开始
让 Node.js 后端服务上报日志 + 自定义 metric + 分布式 trace span,并经 W3C traceparent 与
端上 SDK 端到端贯通。v0 仅依赖 Node 内建模块(node:crypto / node:http / node:async_hooks),
零第三方运行时依赖。协议与 Go 版、Web 版逐字节一致,可混合部署在同一条 trace 上。
对应 SDK:sdks/node-backend ·
示例:examples/node-backend-demo
安装
npm install @argus/sdk-node-backendimport { init } from "@argus/sdk-node-backend";初始化 + 中间件(Express)
import express from "express";
import { init } from "@argus/sdk-node-backend";
const argus = init({
dsn: process.env.ARGUS_DSN!, // argus://public:secret@host:port/project
serviceName: "checkout-api",
release: "v1.2.3",
sampleRate: 1, // trace 头部采样率 [0,1],0/缺省=全采;error span 始终保留
});
const app = express();
// Middleware:继承入站 traceparent → 创建 server span → 经 AsyncLocalStorage 设为 active → 上报。
app.use(argus.middleware());
// 进程退出前 flush 缓冲、停止后台定时器。
process.on("SIGTERM", () => argus.close());
app.listen(8080);上报(日志 / metric / span)
app.post("/api/order", async (req, res) => {
// 日志自动携带本请求 trace_id(从 AsyncLocalStorage 提取)。
argus.info("order received", { attrs: { user_id: "u-42" } });
// metric:counter / gauge / histogram。
argus.counter("orders.placed", 1, { region: "us" });
// 手动子 span(自动接当前 server span 为 parent)。
const span = argus.startSpan("charge-card");
span.setAttribute("db.system", "postgres");
span.setStatus("ok").finish();
res.sendStatus(200);
});端到端 Trace:把链路传给下游
出站请求注入 traceparent,下游服务(同套 SDK 或 Go 版)继承同一条 trace:
// withSpan:在新 span 的上下文内执行 fn,结束自动 finish;fn 内的 log / startSpan /
// traceHeaders 自动接到这条 span。
await argus.withSpan("call order-service", async (span) => {
span.setAttribute("peer.service", "order-service");
await fetch("http://order-service/reserve", {
headers: { ...argus.traceHeaders() }, // ★ 注入 traceparent
});
}, { kind: "client" });- 传播:active span 放进
AsyncLocalStorage(Node 惯例,等价于 Go 的context.Context)。 - 采样一致:按
trace_id做 FNV-1a 一致性 hash,与 Web / Go SDK 同算法、同向量。
详见 端到端 Trace 指南。
Go 版 API 对照
| 能力 | Go | Node |
|---|---|---|
| 初始化 | argus.New(Config) | init(config) |
| 日志 | client.Info(ctx, msg, attrs) | client.info(msg, { attrs }) |
| 手动 span | client.StartSpan(ctx, name) | client.startSpan(name, opts) |
| 自动传播 | 显式 ctx 透传 | client.withSpan(name, fn)(AsyncLocalStorage) |
| 出站注入 | argus.TraceparentFromContext(ctx) | client.traceHeaders() |
差异仅为语言习惯:Go 用显式 ctx 传参,Node 用 AsyncLocalStorage 隐式传播。
运行示例
cd examples/node-backend-demo
npm install
ARGUS_DSN='argus://demo-public:demo-secret@localhost:4318/demo' node server.mjs
# 另开终端,模拟端上 SDK 带 traceparent 进来:
curl -H 'traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' \
http://localhost:8080/api/order