简体   繁体   中英

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). X-Ray works as intended for api using express middleware and able to see traces on 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.

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. More in-depth explanation here: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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