shou2017.com
JP

How to use X-Ray with AWS JavaScript SDK (V3)

Sat Sep 18, 2021
Sat Aug 10, 2024
AWS

I had a chance to update some Lambda code from AWSJavaScriptSDK(V2) to V3, so here are my notes.

With AWSJavaScriptSDK(V2), to use X-Ray, you would write something like this, as per the official docs:

var AWS = require('aws-sdk');
var AWSXRay = require('aws-xray-sdk');
var ddb = AWSXRay.captureAWSClient(new AWS.DynamoDB());

Add annotations and metadata to segments with the X-Ray SDK for Node.js

However, with AWS SDK for JavaScript v3, the way you write things has changed a lot. Previously, you had to use the whole aws-sdk, but in V3 you can use individual packages, etc.

const {DynamoDB, CreateTableCommand} = require('@aws-sdk/client-dynamodb');
const dynamodb = new DynamoDB({region: 'us-west-2'});
var tableParams = {
    Table : TABLE_NAME
};
async function run() => {
      try{
           const data = await dynamodb.send(new CreateTableCommand(tableParams));
           console.log("Success", data);
      } 
      catch (err) {
           console.log("Error", err);
      }
};
run(); 

What’s the AWS SDK for JavaScript?

To use X-Ray with V3, do it like this:

const AWSXRay = require('aws-xray-sdk');
import { S3, PutObjectCommand } from '@aws-sdk/client-s3';

const s3 = AWSXRay.captureAWSv3Client(new S3({}));

await s3.send(new PutObjectCommand({
  Bucket: bucketName,
  Key: keyName,
  Body: 'Hello!',
}));

As you can see with captureAWSv3Client, it works with the client. It does not work with Command.

aws-xray-sdk-core

参考

See Also