如何不使用Express中间件为node.js应用配置AWS X-Ray?

时间:2019-07-04 05:19:28

标签: node.js express aws-xray distributed-tracing application-monitoring

我正在尝试将AWS X-Ray与托管在AWS Lambda(无服务器)上的nodejs api集成。 X-Ray使用快速中间件按预期用于api的方式工作,并且能够在AWS Console上查看跟踪。 对于没有快速框架的异步功能,我在集成时会遇到问题。

尝试启用手动模式,但遇到- Lambda不支持手动模式错误。

引荐的this-为自动模式开发自定义解决方案,但没有运气。

有人可以帮我吗?

'use strict';
const AWSXRay = require('aws-xray-sdk-core');
const Aws = AWSXRay.captureAWS(require('aws-sdk'))
const capturePostgres = require('aws-xray-sdk-postgres');
const { Client } = capturePostgres(require('pg'));

module.exports.test = async (event, context) => {
         var ns = AWSXRay.getNamespace();
         const segment = newAWSXRay.Segment('Notifications_push');
         ns.enter(ns.createContext());
         AWSXRay.setSegment(segment_push);
         .... };

1 个答案:

答案 0 :(得分:0)

因此,在Lambda中时,SDK会自动创建一个占位符(外观)段。此处有更深入的说明:https://github.com/aws/aws-xray-sdk-node/issues/148

您需要的是:

const AWSXRay = require('aws-xray-sdk-core');
//lets patch the AWS SDK
const Aws = AWSXRay.captureAWS(require('aws-sdk'));

module.exports.test = async (event, context) => {
  //All capturing will work out of box

  var sqs = new AWS.SQS({apiVersion: '2012-11-05'});
  var params = {...}

  //no need to add code, just regular SQS call
  sqs.sendMessage(params, function(err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data.MessageId);
    }
  });

  //if you want to create subsegments manually simply do
  const seg = AWSXRay.getSegment();
  const subseg = seg.addSubsegment('mynewsubsegment');
  subseg.close();
  //no need to close the Lambda segment
};

此处的其他文档:https://docs.aws.amazon.com/lambda/latest/dg/nodejs-tracing.html