如何使用AWS X-Ray跟踪Axios HTTP请求?

25

我在寻找一种方法,在基于 Node.js 的 AWS Lambda 函数中跟踪 Axios HTTP 请求。我已经在 AWS 官方文档中找到了一种跟踪 HTTP 请求的方法。 https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-httpclients.html

var AWSXRay = require('aws-xray-sdk');
var http = AWSXRay.captureHTTPs(require('http'));

但是我没有找到关于axios请求跟踪的文档或博客。我也尝试了这段代码,但它没有起作用。

import AWSXRay from 'aws-xray-sdk';
AWSXRay.captureHTTPsGlobal("../../common/http/HttpClient");
import { HttpClient } from "../../common/http/HttpClient";

我需要在这方面得到帮助。谢谢!


你好,能否详细说明一下“它不起作用”的情况?你是否遇到了任何错误或者是缺少http信息?你使用的是什么语法或代码片段来使用axios进行http调用?请注意,AWS X-Ray SDK for Nodejs并不正式支持axios,你可以在这里查看内置http客户端的修补代码 https://github.com/aws/aws-xray-sdk-node/blob/master/packages/core/lib/patchers/http_p.js。 - haotian465
嗨,我在我的lambda函数中添加这些行时没有收到任何错误。import AWSXRay from 'aws-xray-sdk'; AWSXRay.captureHTTPsGlobal("../../common/http/HttpClient"); import { HttpClient } from "../../common/http/HttpClient";实际上,在我的lambda函数中,我正在进行axios post请求并测试返回500代码的端点。理想情况下,此错误应通过aws x-ray记录,但它没有记录错误。但是在部署时会打印此消息:“AWS_XRAY_CONTEXT_MISSING已设置。将配置的上下文丢失策略设置为LOG_ERROR” - Zeeshan Tariq
@haotian465,我刚刚发现了一种使用captureAsyncFunc记录axios错误的方法,但我想知道是否可以将其转换为promise,以使代码更清晰。我在这里添加了代码片段:https://jsfiddle.net/zeeshantariq/1b68eLdr/77938/ 但是我得到了错误:Error: Param "fcn" must be a function. - Zeeshan Tariq
此事项已列入待办事项。您可以在 https://github.com/aws/aws-xray-sdk-node 打开一个问题或提交一个用于Promisifying Capture的PR。 - haotian465
2个回答

22

由于 axios 在底层使用了 Node 的 http/https 模块,因此如果在导入/引用 axios 之前全局捕获 http 和 https,那么事情应该会按预期进行。

import AWSXRay from 'aws-xray-sdk';
import http from 'http';
import https from 'https';

AWSXRay.captureHTTPsGlobal(http);
AWSXRay.captureHTTPsGlobal(https);

const axios = require('axios');

1

一个简单的例子,应该可以直接运行:

const
  axios = require('axios'),
  AWSXRay = require('aws-xray-sdk-core');

AWSXRay.captureHTTPsGlobal(require('http')); // Globally instrument http client
AWSXRay.captureHTTPsGlobal(require('https')); // Globally instrument https client

const http = require('http');
const https = require('https');

AWSXRay.capturePromise(); // We should capture promies
const instance = axios.create({
  httpAgent: new http.Agent(),
  httpsAgent: new https.Agent(),
}); // Instrument axious instance

const post = async (url, body) => {
  return await instance.post(url, body);
}

确保Lambda具有正确的访问权限。


这行代码不起作用,它说 capturePromise 不是一个函数。这些变量需要在哪里声明?全局声明吗? - user2763557

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接