简体   繁体   English

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

[英]How to Configure AWS X-Ray for node.js app not using Express middleware?

I am trying to integrate AWS X-Ray with my nodejs api hosted on AWS Lambda(serverless). 我正在尝试将AWS X-Ray与托管在AWS Lambda(无服务器)上的nodejs api集成在一起。 X-Ray works as intended for api using express middleware and able to see traces on AWS Console. X-Ray使用快速中间件按预期用于api的方式工作,并且能够在AWS Console上查看跟踪。 For async functions without express framework, I am facing issues while integration. 对于没有快速框架的异步功能,我在集成时会遇到问题。

Tried enabling Manual mode, but facing- Lambda not supporting manual mode error. 尝试启用手动模式,但面临-Lambda 不支持手动模式错误。

Referred this - Developing custom solutions for automatic mode section but no luck. 引用了 - 开发自动模式的自定义解决方案部分,但没有运气。

Can someone help me out with 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);
         .... };

So, when in Lambda, the SDK creates a placeholder (facade) segment automatically. 因此,在Lambda中时,SDK会自动创建一个占位符(外观)段。 More in-depth explanation here: https://github.com/aws/aws-xray-sdk-node/issues/148 此处有更深入的说明: https//github.com/aws/aws-xray-sdk-node/issues/148

All you need is: 所有你需要的是:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM