插桩 HTTP 请求

了解如何手动插桩代码以使用 Sentry 的 Requests 模块。

在设置 Requests 之前,您需要首先 设置追踪。完成此操作后,JavaScript SDK 将自动为传出的 HTTP 请求进行插桩。如果这不符合您的使用场景,请按照本指南手动插桩您的请求。

有关可以设置哪些数据的详细信息,请参阅 Requests 模块开发规范

请参阅 HTTP 跨度数据约定,以获取完整的跨度数据属性列表。

以下是一个插桩后的函数示例,该函数执行 HTTP 请求:

my-request.js
Copied
async function makeRequest(method, url) {
  return await Sentry.startSpan(
    { op: "http.client", name: `${method} ${url}` },
    async (span) => {
      const parsedURL = new URL(url, location.origin);

      span.setAttribute("http.request.method", method);

      span.setAttribute("server.address", parsedURL.hostname);
      span.setAttribute("server.port", parsedURL.port || undefined);

      const response = await fetch(url, {
        method,
      });

      span.setAttribute("http.response.status_code", response.status);
      span.setAttribute(
        "http.response_content_length",
        Number(response.headers.get("content-length")),
      );

      // A good place to set other span attributes

      return response;
    },
  );
}