OpenTelemetry 在前端的落地
MrSmy Lv5

后端用 OpenTelemetry 已经几年了,一次请求从网关到服务到数据库的链路在 Jaeger 里一目了然。但链路的前 3 秒(浏览器渲染 + 用户交互)是黑盒——用户说”点了一下很慢”,你在后端 trace 里找不到对应的请求。

这篇讲我们怎么把前端接进同一条 trace。

核心问题:前端能产出什么 trace

后端的 trace 是”函数调用的嵌套”,前端不一样:

1
2
3
4
5
6
用户点击
├─ 事件处理(可能 200ms 的同步计算)
├─ fetch /api/orders ← 这个能变成 span
│ └─ (后端 trace)
├─ 渲染更新(React commit)
└─ 浏览器绘制

能变成有意义的 span 的主要是:

环节 是否能成为 span 价值
页面加载(navigation) ✅ 高(能关联后端)
fetch/XHR ✅ 很高(直连后端 trace)
用户交互(click 到渲染完成) ⚠️ 需要手动埋 高(INP 归因)
React 渲染 ⚠️ 需要 patch 中
资源加载 ⚠️ 低(已有 Resource Timing)

**最有价值的是”fetch 的 span”**——因为它能把前端 span 和后端 trace 串成一条链路。

原理:W3C traceparent

跨服务传递 trace 靠一个 HTTP 头:

1
2
3
4
5
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
│ │ │ │
│ trace-id(32 hex) parent-span-id flags
│
version

前端只要能生成并带上这个头,后端就能接上。

关键决策:谁来生成 trace-id?

  • 方案 A:后端返回,前端通过响应头拿到——页面加载时的 HTML 响应可以带 traceparent,前端用它作为根。
  • 方案 B:前端自己生成——前端是”用户操作的发起者”,trace 从前端开始更符合直觉。

我们用方案 B(前端生成 trace-id),因为一个页面生命周期内会有多次用户操作,每次操作是独立的 trace 比”一个页面一个 trace”更合理。

接入 OTel 浏览器 SDK

1
2
3
4
5
6
npm i @opentelemetry/api @opentelemetry/sdk-trace-web \
@opentelemetry/instrumentation-fetch \
@opentelemetry/instrumentation-document-load \
@opentelemetry/instrumentation-user-interaction \
@opentelemetry/exporter-trace-otlp-http \
@opentelemetry/resources @opentelemetry/semantic-conventions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// telemetry.ts
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web'
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { resourceFromAttributes } from '@opentelemetry/resources'
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'
import { registerInstrumentations } from '@opentelemetry/instrumentation'
import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch'
import { DocumentLoadInstrumentation } from '@opentelemetry/instrumentation-document-load'
import { UserInteractionInstrumentation } from '@opentelemetry/instrumentation-user-interaction'
import { ZoneContextManager } from '@opentelemetry/context-zone'

const exporter = new OTLPTraceExporter({
url: '/otlp/v1/traces',
headers: { 'x-api-key': __OTEL_KEY__ },
})

const provider = new WebTracerProvider({
resource: resourceFromAttributes({
[ATTR_SERVICE_NAME]: 'web',
[ATTR_SERVICE_VERSION]: __APP_VERSION__,
'deployment.environment': __APP_ENV__,
}),
spanProcessors: [
new BatchSpanProcessor(exporter, {
maxQueueSize: 100,
scheduledDelayMillis: 5000,
exportTimeoutMillis: 3000,
}),
],
})

provider.register({
contextManager: new ZoneContextManager(), // 异步上下文传播需要
})

registerInstrumentations({
instrumentations: [
new DocumentLoadInstrumentation(),
new FetchInstrumentation({
propagateTraceHeaderCorsUrls: [
/^https:\/\/api\.example\.com/,
/^\/api\//, // 同源
],
clearTimingResources: true,
}),
new UserInteractionInstrumentation({
eventNames: ['click', 'submit'],
}),
],
tracerProvider: provider,
})

最容易踩的坑:CORS

前端要往 api.example.com 发请求并带上 traceparent 头,这会触发预检请求(OPTIONS)——因为 traceparent 是自定义头。

后端必须:

1
2
3
4
5
6
7
8
9
10
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'https://www.example.com')
res.setHeader(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, traceparent, tracestate' // ← 必须加这两个
)
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
if (req.method === 'OPTIONS') return res.sendStatus(204)
next()
})

漏了这一步的表现:所有跨域请求失败,控制台报 CORS 错误。很多人以为是 OTel 配置问题,实际是后端的 Allow-Headers。

另一个坑:预检请求本身也会被 OTel 记录成 span,产生大量噪音。要在 FetchInstrumentation 里过滤:

1
2
3
4
new FetchInstrumentation({
ignoreUrls: [/\/health$/, /\/favicon\.ico$/],
// 预检请求在浏览器里不经过 fetch hook,一般不会产生 span
})

实际上预检是浏览器内部发的,不经过 JS 的 fetch,所以不产生 span。但后端会收到 OPTIONS 请求,要确保它不产生后端 span(很多后端框架会为 OPTIONS 建立 trace)。

和 Zone.js 的冲突

ZoneContextManager 依赖 Zone.js。如果你的项目是 Angular,Zone.js 本来就在;如果是 React/Vue,引入 Zone.js 会有代价:

  • 体积 +40KB(gzip 后 12KB)
  • 会 patch 所有异步 API,有性能开销
  • 和某些库冲突(比如已经 patch 过 Promise 的 polyfill)

替代方案:用 W3CTraceContextPropagator + 手动传播

1
2
3
provider.register({
// 不指定 contextManager,用默认的(只支持同步上下文)
})

代价是异步链路会断:

1
2
3
const span = tracer.startSpan('checkout')
await fetch('/api/cart') // 这个 fetch 的 parent 是 "checkout" 吗?
// 如果没有 context manager,可能不是

实际上 FetchInstrumentation 内部会读 OTel 的 active context,默认的 AsyncLocalStorageContextManager(Node)在浏览器不可用。浏览器里只能用 Zone.js 或者手动传 context:

1
2
3
4
5
6
7
8
import { context, trace } from '@opentelemetry/api'

const span = tracer.startSpan('checkout')
await context.with(trace.setSpan(context.active(), span), async () => {
await fetch('/api/cart') // 现在 parent 正确了
await fetch('/api/pay')
})
span.end()

我们的选择:只在”手动埋点的地方”用 context.with,不引入 Zone.js。

理由:40KB 的体积换”自动传播”,在 C 端产品上不划算;而且我们真正需要串联的链路(下单、支付)本来就是手动埋的。

手动埋点:把”用户操作”变成 span

自动 instrumentation 覆盖不了”业务语义”。真正的价值在手动埋点:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { trace, SpanStatusCode } from '@opentelemetry/api'

const tracer = trace.getTracer('web')

export async function checkout(cart: Cart) {
return tracer.startActiveSpan('checkout', async (span) => {
span.setAttributes({
'cart.items': cart.items.length,
'cart.total': cart.total,
'user.id': getUserId(),
})

try {
// 1. 创建订单
const order = await tracer.startActiveSpan('checkout.create-order', async (s) => {
const res = await api.createOrder(cart)
s.setAttribute('order.id', res.id)
s.end()
return res
})

// 2. 支付
await tracer.startActiveSpan('checkout.pay', async (s) => {
s.setAttribute('pay.method', cart.payMethod)
await api.pay(order.id, cart.payMethod)
s.end()
})

span.setStatus({ code: SpanStatusCode.OK })
return order
} catch (e) {
span.recordException(e)
span.setStatus({ code: SpanStatusCode.ERROR, message: e.message })
throw e
} finally {
span.end()
}
})
}

**更实用的是”包装器”**——避免每次手写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
export function traced<A extends any[], R>(
name: string,
fn: (...args: A) => Promise<R>,
attrs?: (args: A) => Record<string, unknown>
) {
return async (...args: A): Promise<R> => {
return tracer.startActiveSpan(name, async (span) => {
try {
if (attrs) span.setAttributes(attrs(args) as any)
const result = await fn(...args)
span.setStatus({ code: SpanStatusCode.OK })
return result
} catch (e) {
span.recordException(e as Error)
span.setStatus({ code: SpanStatusCode.ERROR })
throw e
} finally {
span.end()
}
})
}
}

// 使用
const submitOrder = traced('order.submit', async (cart: Cart) => {
return api.submit(cart)
}, ([cart]) => ({ 'cart.items': cart.items.length }))

把”交互到渲染”也纳入测量

INP 的核心是”点击到下一帧绘制完成”。要归因到具体代码,需要手动测量:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
export function measureInteraction(name: string, fn: () => void) {
const start = performance.now()

// 用 performance.mark 做标记(DevTools 里也能看到)
performance.mark(`${name}:start`)

fn()

// 等下一帧绘制完成
requestAnimationFrame(() => {
// 双重 rAF 才是"绘制完成"
requestAnimationFrame(() => {
const duration = performance.now() - start
performance.mark(`${name}:end`)
performance.measure(name, `${name}:start`, `${name}:end`)

if (duration > 100) {
tracer.startActiveSpan(`interaction.${name}`, (span) => {
span.setAttribute('interaction.duration_ms', duration)
span.setAttribute('interaction.slow', true)
span.end()
})
}
})
})
}

用法:

1
2
3
<button onClick={() => measureInteraction('filter-apply', () => applyFilters(filters))}>
应用筛选
</button>

这样”哪些交互慢”直接变成了 trace 数据,能在 Jaeger 里和对应的后端 span 对照看。

数据量:真正的问题

一个中型应用(DAU 5 万)接入一周后的数据量:

1
2
3
4
每天 trace 数:   1,200,000
平均 span/trace: 4.2
每天 span 数: 5,040,000
每天数据: 约 8.6GB(未压缩)

存储成本会失控。必须采样。

1. 头部采样(Head Sampling)

1
2
3
4
const provider = new WebTracerProvider({
sampler: new TraceIdRatioBasedSampler(0.05), // 5%
// ...
})

优点:简单,开销小(不采样的 trace 完全不收集)。
缺点:丢失的 trace 无法补救——出问题时想查完整链路,可能恰好没采到。

2. 尾采样(Tail Sampling)

前端做不到(需要等服务端收集完再决定)。要在 OTel Collector 里配:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# otel-collector-config.yaml
processors:
tail_sampling:
decision_wait: 10s
policies:
- name: errors
type: status_code
status_code: { status_codes: [ERROR] }
- name: slow
type: latency
latency: { threshold_ms: 3000 }
- name: sample-rest
type: probabilistic
probabilistic: { sampling_percentage: 5 }

“错误全留 + 慢请求全留 + 其余 5%” 是最实用的策略。前端只要全量上报,Collector 层做决策。

代价:前端全量上报意味着带宽和导出开销在前端(BatchSpanProcessor 会攒批,影响可控)。

我们的实际配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
// 前端:全量采集,但控制队列大小
new BatchSpanProcessor(exporter, {
maxQueueSize: 200,
scheduledDelayMillis: 10000, // 10 秒攒一批
maxExportBatchSize: 100,
})

// 客户端侧也做一层采样(减少上报量)
sampler: new ParentBasedSampler({
root: new TraceIdRatioBasedSampler(0.2), // 20%
})
// ParentBased:如果后端返回的 traceparent 里标记了"采样",
// 前端跟着采(保证链路完整)

ParentBasedSampler 很重要——如果后端已经决定采这个 trace,前端不应该独立决定”不采”,否则链路就断了。

页面关闭时丢 span 的问题

BatchSpanProcessor 会攒 10 秒再发。用户 3 秒后就关了页面,这些 span 全丢了。

解法:

1
2
3
4
5
6
7
8
9
window.addEventListener('pagehide', () => {
provider.forceFlush() // 同步触发导出
})

document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
provider.forceFlush()
}
})

但 forceFlush 是异步的,页面关闭时可能来不及。真正可靠的做法是 sendBeacon:

1
2
3
4
5
6
7
8
9
10
11
12
13
// 在 exporter 层做特殊处理
class BeaconExporter implements SpanExporter {
export(spans: ReadableSpan[], resultCallback) {
const body = JSON.stringify(serialize(spans))
if (document.visibilityState === 'hidden') {
navigator.sendBeacon('/otlp/v1/traces', body)
} else {
fetch('/otlp/v1/traces', { method: 'POST', body, keepalive: true })
}
resultCallback({ code: ExportResultCode.SUCCESS })
}
shutdown() { return Promise.resolve() }
}

这是一个”必须自己做”的补丁——OTel 的官方 exporter 没有处理这个场景。

一个真实的收益

我们上线后的第一个”抓到的问题”:

1
2
3
4
5
6
7
span: checkout
├─ checkout.create-order 4,820ms ← 异常
│ └─ POST /api/orders 4,800ms
│ └─ (后端) order.create 4,780ms
│ └─ db.transaction 4,750ms
│ └─ UPDATE inventory ... 4,700ms ← 锁等待
├─ checkout.pay 320ms

从前端点击到数据库锁等待,一条链路看完。以前要三个人(前端、后端、DBA)各自查日志对齐时间戳。

这个能力是 OTel 最大的价值——**不是”更多数据”,是”关联”**。

成本与收益的权衡

规模 建议
小项目(DAU < 5000) 用 Sentry 这类 SaaS(省事,成本可控)
中型(DAU 1-10 万) 自建 OTel + Collector + Jaeger/Tempo,采样 5-20%
大型(DAU > 10 万) 必须尾采样 + 分层存储(热数据 7 天,冷数据抽样归档)

前端接入 OTel 的成本主要在:

  1. 后端要支持 CORS 的 traceparent 头
  2. 要有 Collector(不能直连 Jaeger)
  3. 采样策略要调(否则存储爆炸)
  4. 团队要理解”span / trace / context”概念

收益:

  • 跨端链路排查(前端 → 网关 → 服务 → DB)
  • 慢请求归因(”这个接口慢”变成”这个接口里哪一步慢”)
  • 前后端对齐(不用猜”是不是前端慢”还是”后端慢”)

小结

前端接 OTel 的三个关键决策:

决策 我们的选择 理由
trace 根在哪 前端生成 用户操作是链路起点
上下文传播 手动 context.with,不用 Zone.js 12KB 体积换自动化不划算
采样 前端 20% + Collector 尾采样 错误和慢请求全留

最容易出错的三个地方:

  1. CORS 的 Allow-Headers 忘了 traceparent
  2. 页面关闭时 span 丢失(要自己实现 beacon exporter)
  3. 采样导致链路断裂(要用 ParentBasedSampler)

一个判断:如果你的团队已经在后端用 OTel,前端接入的边际成本很低(共享 Collector 和存储),收益明显。如果后端还没用,先别从前端开始——前端的 trace 没有后端接应就只是”更复杂的日志”。

  • 本文标题:OpenTelemetry 在前端的落地
  • 本文作者:MrSmy
  • 创建时间:2025-07-20 20:33:00
  • 本文链接:https://fengyang.live/2025/07/20/OpenTelemetry在前端的落地/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!