Search code examples
aws-lambdaaws-sam-cliaws-xray

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?


Solution

  • 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()
    }