通过拦截 fetch 全局构造函数并挂载自定义属性来实现接口请求链路追踪。具体做法是保存原始 window.fetch,重写一个包装函数,在调用前后记录时间戳、url 和状态码,并将这些元数据绑定到返回的 promise 对象上,从而让调用方能够获取完整的请求生命周期信息。

如何拦截 fetch 并注入追踪逻辑
直接覆盖 window.fetch 是最基础且有效的切入点。我们需要定义一个唯一的标识符来区分被追踪的请求,避免污染其他库或原生行为。在重写后的函数中,先发起实际的 HTTP 请求,然后利用 Promise 链将追踪数据附加到响应对象上。

const originalFetch = window.fetch;
window.fetch = async function(...args) {
const traceId = Math.random().toString(36).slice(2);
const startTime = performance.now();
try {
const response = await originalFetch.apply(this, args);
const endTime = performance.now();
// 将追踪信息挂载到响应对象上
response.traceInfo = {
traceId,
url: args[0],
duration: endTime - startTime,
status: response.status,
timestamp: Date.now()
};
return response;
} catch (error) {
const endTime = performance.now();
throw Object.assign(error, {
traceId,
url: args[0],
duration: endTime - startTime,
errorType: 'NetworkError',
timestamp: Date.now()
});
}
};上述代码展示了核心实现。当调用 fetch 时,系统会生成一个 traceId,计算耗时,并在成功时将 traceInfo 附加到 Response 实例。如果发生网络错误,异常对象也会被扩展以包含相同的追踪字段。这种方式对业务代码侵入性极低,只需检查返回值的 traceInfo 即可。
立即学习“Java免费学习笔记(深入)”;
如何处理并发请求与上下文关联
在实际应用中,多个请求可能同时发出,简单的随机 ID 可能导致日志混乱。更好的做法是结合异步上下文(AsyncContext)或请求队列来管理链路。我们可以维护一个简单的栈结构,确保每个请求都能找到其父级上下文,或者为每个请求分配独立的追踪作用域。

// 简化的上下文管理器示例
const TraceContext = {
stack: [],
currentTraceId: null,
push(traceId) {
this.stack.push({ traceId, start: Date.now() });
this.currentTraceId = traceId;
},
pop() {
const ctx = this.stack.pop();
this.currentTraceId = this.stack.length > 0 ? this.stack[this.stack.length - 1].traceId : null;
return ctx;
},
getCurrent() {
return this.stack.length > 0 ? this.stack[this.stack.length - 1] : null;
}
};
// 在 fetch 中使用
window.fetch = async function(...args) {
const traceId = TraceContext.getCurrent()?.traceId || Math.random().toString(36).slice(2);
TraceContext.push(traceId);
try {
const response = await originalFetch.apply(this, args);
response.traceInfo = { ...response.traceInfo, parentId: traceId };
return response;
} finally {
TraceContext.pop();
}
};通过引入 TraceContext,我们可以模拟调用栈的行为。虽然 JavaScript 的单线程特性使得真正的并行难以完全隔离,但这种栈式管理能很好地处理嵌套请求或需要父子关联的场景。每个请求都会携带其生成的 traceId,并在完成后从栈中移除,保持上下文的清洁。
基于 traceId 的具体查询与过滤
当系统中积累了大量带有 traceId 的请求后,开发者通常需要根据特定的 traceId 来筛选出该链路下的所有日志或性能数据。这要求我们在前端存储或上报后端时,保留这个唯一标识。例如,在控制台打印或发送到分析平台时,可以按 traceId 进行分组。
假设我们有一个具体的请求 URL /api/user/profile,我们可以通过遍历之前捕获的 traceInfo 集合,找出所有 url 匹配且 traceId 相同的条目。这种机制对于排查特定接口的慢查询或失败原因非常有效。开发者只需关注那个特定的 traceId,就能还原整个请求的生命周期,包括网络延迟、服务器处理时间和最终的状态码变化。


















