19

我正在寻找一种在基于 node.js 的 aws lambda 函数中跟踪 axios http 请求的方法。我找到了一种在 aws 官方文档 https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-httpclients.html上跟踪 HTTP 请求的方法

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";

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

4

2 回答 2

16

由于 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');
于 2018-12-06T20:34:21.853 回答
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 具有正确的访问权限。

于 2019-12-27T21:06:50.037 回答