Search code examples
pythonaws-lambdaaws-xray

AWS Xray: Cannot create segments inside Lambda function and segment not found


A really strange behaviour I was experiencing, I am following online documentation and while creating a segment to work with my subsegment, the lambda executes in following order:

xray_recorder.begin_segment('segment-name')
xray_recorder.begin_subsegment('subsegment-name')
# put annotations and meta data etc
xray_recorder.end_segment('segment-name')
xray_recorder.end_subsegment('subsegment-name')

but I get following error on CloudWatch Manager:

Cannot create segments inside Lambda function. Discarded.

When I remove segment creation and try running things locally like this:

xray_recorder.begin_subsegment('subsegment-name')
# put annotations and meta data etc
xray_recorder.end_segment('segment-name')

I get the error: SegmentNotFoundException: cannot find the current segment/subsegment, please make sure you have a segment open

Confusing.


Solution

  • While running locally xray segments are created locally and you have to initiate segments for creating sub-segments but while running on lambda on AWS, the segments are created by default and you can proceed with sub-segments.

    Locally I was running into errors while omitting the creation of segments while it worked fine remotely.