Search code examples
pythonamazon-web-servicesaws-xray

How to set segment (top) level AWS Xray annotations in Python Lambda


I am successfully using AWS Xray within a Python v2 Lambda. The patch_all() is working well to automatically patch a portion of my libraries, i.e boto3, for Xray.

I am unable to set high level annotations that persist across the lower level subsegments. Can annotations in lambda be set like this? If not how else should they be set? I've tried getting current subsegment and segment.

import json
import re
import boto3
import logging
import sys

from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all

patch_all()

def lambda_handler(event, context):  
  subsegment_ref = xray_recorder.current_subsegment()
  subsegment_ref.put_annotation('account_id', 'foo')

Solution

  • Lambda function segment is not generated by X-Ray SDK. We are working with Lambda team to provide better experience but currently there is no workaround to annotate the segment.

    For annotating subsegment, you can create a subsegment inside the handler and then add annotation to it. You can see the quick start guide https://github.com/aws/aws-xray-sdk-python for creating custom subsegment.

    The easiest way is using context manager style:

    with xray_recorder.in_subsegment('pick_a_subsegment_name') as subsegment:
            subsegment.put_annotation('key', 'value')