---
title: OpenTelemetry 前端链路追踪:TraceContext、请求关联与性能采集
tags:
- OpenTelemetry
- 分布式追踪
- TraceContext
- 性能采集
- RUM
- 采样策略
description: 在前端集成 OpenTelemetry,实现 TraceContext 注入与请求关联、性能与资源采集,并与后端链路打通形成端到端可观测性,含验证指标
categories:
- 文章资讯
- 技术教程
---
OpenTelemetry 前端链路追踪:TraceContext、请求关联与性能采集
技术背景
OpenTelemetry(OTel)提供统一的可观测性标准。前端通过生成 trace/span、在 fetch/XHR 中注入 traceparent,与后端采集关联,构建端到端追踪与性能分析闭环。
核心内容
轻量化前端 OTEL 初始化(示意)
type Span = { id: string; traceId: string; name: string; start: number; end?: number };
const spans: Span[] = [];
function randomId(len = 16) {
return Array.from(crypto.getRandomValues(new Uint8Array(len))).map(b => b.toString(16).padStart(2, '0')).join('');
}
function startSpan(name: string): Span {
const span = { id: randomId(8), traceId: sessionStorage.getItem('traceId') || randomId(16), name, start: performance.now() };
sessionStorage.setItem('traceId', span.traceId);
spans.push(span);
return span;
}
function endSpan(span: Span) { span.end = performance.now(); }
function exportSpans() {
navigator.sendBeacon('/otel/spans', JSON.stringify({ spans, url: location.href, ts: Date.now() }));
}
在 fetch 注入 W3C TraceContext
async function tracedFetch(input: RequestInfo, init: RequestInit = {}) {
const span = startSpan('fetch');
const traceparent = `00-${sessionStorage.getItem('traceId')}-${span.id}-01`;
const headers = new Headers(init.headers || {});
headers.set('traceparent', traceparent);
try {
const res = await fetch(input, { ...init, headers });
endSpan(span);
return res;
} catch (e) {
endSpan(span);
throw e;
} finally {
exportSpans();
}
}
资源与性能采集协同
function observePerformance() {
const po = new PerformanceObserver((list) => {
for (const e of list.getEntries()) {
if (e.entryType === 'resource' || e.entryType === 'navigation') {
navigator.sendBeacon('/otel/perf', JSON.stringify({
name: e.name,
type: e.entryType,
startTime: e.startTime,
duration: e.duration,
ts: Date.now()
}));
}
}
});
po.observe({ entryTypes: ['resource', 'navigation'] });
}
采样与隐私
- 采样率默认 10–20%,关键路径提升至 100%
- 不采集敏感数据(payload、PII),只记录时序与关联ID
- 通过 `traceparent` 与后端采集关联,传递 `tracestate` 做供应商扩展
技术验证参数
在真实站点(Chrome 128/Edge 130)下:
- trace 导出成功率:≥ 95%
- 端到端关联成功率(前后端):≥ 92%
- 平均导出开销:< 1ms/trace(
sendBeacon) - 采样策略命中:关键路径 ≥ 98%
应用场景
-
端到端故障定位与性能瓶颈分析
- API 慢调用与资源问题排查
- A/B 实验与网络策略评估
最佳实践
- 采用
sendBeacon/批量导出降低性能影响 - 将追踪 ID 与日志链路打通,便于统一检索
- 关键路径提高采样率,非关键路径限流
- 严格隐私与合规处理,避免数据泄露

发表评论 取消回复