Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I invoke a SAM Lambda function locally with X-Ray statements?

I'm receiving the following error when invoking an AWS SAM Lambda function locally:

Missing AWS Lambda trace data for X-Ray. Ensure Active Tracing is enabled and no subsegments are created outside the function handler.

Below you can see my function:

/** Bootstrap */
require('dotenv').config()
const AWSXRay = require('aws-xray-sdk')

/** Libraries*/
const se                = require('serialize-error')

/** Internal */
const logger            = require('./src/utils/logger')
const ExecuteService    = require('./src/service')

/**
 *
 */
exports.handler = async (event) => {    
    const xraySegement = AWSXRay.getSegment()
    
    const message = process.env.NODE_ENV == 'production' ? JSON.parse(event.Records[0].body) : event

    try {
        await ExecuteService(message)
    } catch (err) {
        logger.error({
            error: se(err)
        })

        return err
    }
}

In addition, I have Tracing set to Active in my template.yml.

What part of the documentation am I clearly misreading, missing, or reading over?

like image 247
Sean Lindo Avatar asked Oct 25 '25 04:10

Sean Lindo


2 Answers

For now you can't invoke a SAM lambda locally with X-ray because it is not supported yet.

See

The component does not support X-ray and other Lambda integrations locally.


If you don't care about X-ray and just want your code to work you can check the env variable AWS_SAM_LOCAL to prevent X-ray usage:

let AWSXRay
if (!process.env.AWS_SAM_LOCAL) {
    AWSXRay = require('aws-xray-sdk')
}

// ...
if (!process.env.AWS_SAM_LOCAL) {
    const xraySegement = AWSXRay.getSegment()
}

like image 186
Mickael B. Avatar answered Oct 26 '25 20:10

Mickael B.


I am using SAM CLI, version 1.36.0 I noticed importing aws-xray-sdk does not create this issue but invoking the functions do.

To not have a million if statements I created a middle man service that imports aws-xray-sdk then exports noops if the env var process.env.AWS_SAM_LOCAL is set.

like image 33
Michael Warner Avatar answered Oct 26 '25 19:10

Michael Warner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!