AWS XRay:无法写入/tmp/.aws-xray/已初始化。无法通知SDK初始化

时间:2018-12-01 10:44:09

标签: python amazon-web-services aws-lambda aws-xray

我正在尝试编写Lambda函数以将数据存储在dyanamodb中,并尝试与AWS Xray集成。以下是Lambda函数的代码。我遇到了错误

  

无法写入/tmp/.aws-xray/已初始化。无法通知SDK   初始化。由于Lambda工人而丢弃的细分市场put_item   仍在初始化

我安装了Aws xray SDK软件包。此外,代码中还包含开始段和结束段。并将环境变量设置为 LAMBDA_TASK_ROOT 。 请解决此错误。

import json
import os
import configparser
import boto3
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch

patch(['boto3'])
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['dynamodb_table'])

def lambda_handler(event, context):
    for i in event:
        item = {
            'key': i['key'],
            'search': i['search'],
        }
        put_item_into_dynamodb(item)

    response = {
         "statusCode": 200,
         "body": json.dumps(item)
    }
    return response

def put_item_into_dynamodb(item):
    try:
        xray_recorder.begin_subsegment('put_item')
        response = table.put_item(Item=item)
        status_code = response['ResponseMetadata']['HTTPStatusCode']
        xray_recorder.current_subsegment().put_annotation('put_response', status_code)
    finally:
        xray_recorder.end_subsegment()

Update-2(第二个问题):在此代码中 AttributeError:“ NoneType”对象没有属性“ put_annotation” 。此错误即将到来。.我不知道为什么会出现此错误。

def lambda_handler(event, context):

    val = (str(event['userId']),str(event['teamId']), str(event['searchScope']))
    key_table = "|".join(val)
    key = {
        'key': key_table
    }
    response = get_item_into_dynamodb(key)

    try:
        data = response['Item']
        for i in data['search']:
            keyword_list.append(i['searchText'])
            dict_of_keyword[i['searchText']] = i['dateTime']

        recent_sort = sorted(dict_of_keyword.items(), key=lambda x: x[1], reverse=True)
def get_item_into_dynamodb(key):
    try:
        xray_recorder.begin_segment('get_item')
        response = table.get_item(Key = key)
        status_code = response['ResponseMetadata']['HTTPStatusCode']
        xray_recorder.current_subsegment().put_annotation('get_response', status_code) #error is on this line
    finally:
        xray_recorder.end_subsegment()

    return response

1 个答案:

答案 0 :(得分:0)

您无法在Lambda函数中创建细分。 Lambda将在外部包装中创建您无法在函数中访问的段。您可以尝试从xray_recorder.begin_segment('get_item')更改为xray_recorder.begin_subsegment('get_item')吗?

也不会捕获在lambda处理程序外部生成的跟踪数据,因为在此期间,lambda函数仍在初始化并且没有跟踪上下文可用。