Search code examples
pythonaws-lambdaaws-xray

AWS Xray: How to check if Xray Segment is open?


To create a sub-segment aws-xray requires that a valid segment is opened. By default remote lambda execution opens a segment for you and you just have to add a subsegment but while running locally we need to open segment manually before adding sub-segment.

I can put things in try-except block to initiate subsegments only when segments are available but is there any method that checks if segment is open.

Right now working with this:

try:
  xray_recorder.current_segment()
except:
  xray_recorder.begin_segment(self.segment_name)

Solution

  • There is no method dedicated to check if there is an open segment/subsegment or not but the code snippet you posted definitely works well.

    A better way to test a Lambda function locally is to mimic the Lambda container behavior so your instrumented Lambda function behaves exactly the same both locally and in actual Lambda.

    You can check the source code here https://github.com/aws/aws-xray-sdk-python/blob/master/aws_xray_sdk/core/lambda_launcher.py#L24. Basically the Lambda container will set environment variable LAMBDA_TASK_ROOT so the SDK knows it is "running inside Lambda" and create the facade segment based on https://github.com/aws/aws-xray-sdk-python/blob/master/aws_xray_sdk/core/lambda_launcher.py#L94. You can set the trace header to not sample any subsegments so the SDK doesn't generate data.

    It depends on what your local testing is for. The solution might vary depending on if you want to stub X-Ray SDK to test your function or you want to test X-Ray instrumentation and need to see actual data on X-Ray console.