追蹤 TypeScript 程式碼 AWS Lambda - AWS Lambda

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

追蹤 TypeScript 程式碼 AWS Lambda

Lambda 會與 AWS X-Ray 整合,以協助您追蹤、偵錯和最佳化 Lambda 應用程式。您可以使用 X-Ray 來追蹤請求,因為它會周遊您應用程式中的資源,其中可能包含 Lambda 函數和其他 AWS 服務。

若要將追蹤資料傳送至 X-Ray,您可以使用以下三個 SDK 庫之一:

每個 SDK 均提供將遙測資料傳送至 X-Ray 服務的方法。然後,您可以使用 X-Ray 來檢視、篩選應用程式的效能指標並獲得洞察,從而識別問題和進行最佳化的機會。

重要

X-Ray 和適用於 AWS Lambda SDK 的 Powertools 包含在 AWS 提供的緊密整合檢測解決方案中。ADOT Lambda Layers 是用於追蹤檢測之業界通用標準的一部分,這類檢測一般會收集更多資料,但可能不適用於所有使用案例。您可以使用任一解決方案在 X-Ray 中實作 end-to-end 追蹤。若要深入了解如何在兩者之間做選擇,請參閱在 AWS Distro for OpenTelemetry 和 X-Ray SDK 之間進行選擇

使用動力工具進行AWS Lambda(TypeScript)和跟AWS SAM踪

請按照以下步驟下載,構建和部署示例 Hello World TypeScript 應用程序,其中包含集成的 Powertools 的AWS Lambda(TypeScript)模塊使用AWS SAM. 此應用程式實作了基本 API 後端,並使用 Powertools 發送日誌、指標和追蹤。其包含 Amazon API Gateway 端點和 Lambda 函數。當您將 GET 請求傳送至 API Gateway 端點時,Lambda 函數會叫用、使用內嵌指標格式將記錄和指標傳送至 CloudWatch,並將追蹤傳送至AWS X-Ray。該函數會傳回 hello world 訊息。

必要條件

若要完成本節中的步驟,您必須執行下列各項:

部署範例 AWS SAM 應用程式
  1. 使用 Hello World TypeScript 範本初始化應用程式。

    sam init --app-template hello-world-powertools-typescript --name sam-app --package-type Zip --runtime nodejs18.x --no-tracing
  2. 建置應用程式。

    cd sam-app && sam build
  3. 部署應用程式。

    sam deploy --guided
  4. 依照螢幕上的提示操作。若要接受互動體驗中提供的預設選項,請按下 Enter

    注意

    因為HelloWorldFunction 可能沒有定義授權,這可以嗎? ,確保輸入y

  5. 取得已部署應用程式的 URL:

    aws cloudformation describe-stacks --stack-name sam-app --query 'Stacks[0].Outputs[?OutputKey==`HelloWorldApi`].OutputValue' --output text
  6. 調用 API 端點:

    curl <URL_FROM_PREVIOUS_STEP>

    成功的話,您將會看到以下回應:

    {"message":"hello world"}
  7. 若要取得函數的追蹤,請執行 sam 追蹤

    sam traces

    追蹤輸出如下:

    XRay Event [revision 1] at (2023-01-31T11:29:40.527000) with id (1-11a2222-111a222222cb33de3b95daf9) and duration (0.483s) - 0.425s - sam-app/Prod [HTTP: 200] - 0.422s - Lambda [HTTP: 200] - 0.406s - sam-app-HelloWorldFunction-Xyzv11a1bcde [HTTP: 200] - 0.172s - sam-app-HelloWorldFunction-Xyzv11a1bcde - 0.179s - Initialization - 0.112s - Invocation - 0.052s - ## app.lambdaHandler - 0.001s - ### MySubSegment - 0.059s - Overhead
  8. 這是可透過網際網路存取的公有 API 端點。建議您在測試後刪除端點。

    sam delete

X-Ray 無法追蹤應用程式的所有請求。X-Ray 會套用取樣演算法以確保追蹤的效率,同時仍提供所有請求的代表範本。取樣率為每秒 1 次請求和 5% 的額外請求。

注意

您無法針對函數設定 X-Ray 取樣率。

使用動力工具AWS Lambda(TypeScript)和用AWS CDK於跟踪

請按照以下步驟下載,構建和部署示例 Hello World TypeScript 應用程序,其中包含集成的 Powertools 的AWS Lambda(TypeScript)模塊使用AWS CDK. 此應用程式實作了基本 API 後端,並使用 Powertools 發送日誌、指標和追蹤。其包含 Amazon API Gateway 端點和 Lambda 函數。當您將 GET 請求傳送至 API Gateway 端點時,Lambda 函數會叫用、使用內嵌指標格式將記錄和指標傳送至 CloudWatch,並將追蹤傳送至AWS X-Ray。該函數會傳回 hello world 訊息。

必要條件

若要完成本節中的步驟,您必須執行下列各項:

部署範例 AWS Cloud Development Kit (AWS CDK) 應用程式
  1. 為您的新應用程式建立專案目錄。

    mkdir hello-world cd hello-world
  2. 初始化應用程式。

    cdk init app --language typescript
  3. 新增 @types/aws-lambda 套件作為開發相依項。

    npm install -D @types/aws-lambda
  4. 安裝 Powertools Tracer 公用程式

    npm install @aws-lambda-powertools/tracer
  5. 開啟 lib 目錄。您應該會看到一個名為 hello-world-stack.ts 的檔案。在此目錄中建立兩個新檔案:hello-world.function.tshello-world.ts

  6. 開啟 hello-world.function.ts,並將下列程式碼新增至檔案。這是 Lambda 函數的程式碼。

    import { APIGatewayEvent, APIGatewayProxyResult, Context } from 'aws-lambda'; import { Tracer } from '@aws-lambda-powertools/tracer'; const tracer = new Tracer(); export const handler = async (event: APIGatewayEvent, context: Context): Promise<APIGatewayProxyResult> => { // Get facade segment created by Lambda const segment = tracer.getSegment(); // Create subsegment for the function and set it as active const handlerSegment = segment.addNewSubsegment(`## ${process.env._HANDLER}`); tracer.setSegment(handlerSegment); // Annotate the subsegment with the cold start and serviceName tracer.annotateColdStart(); tracer.addServiceNameAnnotation(); // Add annotation for the awsRequestId tracer.putAnnotation('awsRequestId', context.awsRequestId); // Create another subsegment and set it as active const subsegment = handlerSegment.addNewSubsegment('### MySubSegment'); tracer.setSegment(subsegment); let response: APIGatewayProxyResult = { statusCode: 200, body: JSON.stringify({ message: 'hello world', }), }; // Close subsegments (the Lambda one is closed automatically) subsegment.close(); // (### MySubSegment) handlerSegment.close(); // (## index.handler) // Set the facade segment as active again (the one created by Lambda) tracer.setSegment(segment); return response; };
  7. 開啟 hello-world.ts,然後將下列程式碼新增至檔案。其中包含NodejsFunction 建立 Lambda 函數的建構、設定 Powertools 的環境變數,以及將記錄保留設定為一週。它也包含LambdaRestApi 建立 REST API 的建構。

    import { Construct } from 'constructs'; import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; import { LambdaRestApi } from 'aws-cdk-lib/aws-apigateway'; import { CfnOutput } from 'aws-cdk-lib'; import { Tracing } from 'aws-cdk-lib/aws-lambda'; export class HelloWorld extends Construct { constructor(scope: Construct, id: string) { super(scope, id); const helloFunction = new NodejsFunction(this, 'function', { environment: { POWERTOOLS_SERVICE_NAME: 'helloWorld', }, tracing: Tracing.ACTIVE, }); const api = new LambdaRestApi(this, 'apigw', { handler: helloFunction, }); new CfnOutput(this, 'apiUrl', { exportName: 'apiUrl', value: api.url, }); } }
  8. 開啟 hello-world-stack.ts。這是定義 AWS CDK 堆疊的程式碼。將程式碼取代為以下內容:

    import { Stack, StackProps } from 'aws-cdk-lib'; import { Construct } from 'constructs'; import { HelloWorld } from './hello-world'; export class HelloWorldStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); new HelloWorld(this, 'hello-world'); } }
  9. 部署您的應用程式。

    cd .. cdk deploy
  10. 取得已部署應用程式的 URL:

    aws cloudformation describe-stacks --stack-name HelloWorldStack --query 'Stacks[0].Outputs[?ExportName==`apiUrl`].OutputValue' --output text
  11. 調用 API 端點:

    curl <URL_FROM_PREVIOUS_STEP>

    成功的話,您將會看到以下回應:

    {"message":"hello world"}
  12. 若要取得函數的追蹤,請執行 sam 追蹤

    sam traces

    追蹤輸出如下:

    XRay Event [revision 1] at (2023-01-31T11:50:06.997000) with id (1-11a2222-111a222222cb33de3b95daf9) and duration (0.449s) - 0.350s - HelloWorldStack-helloworldfunction111A2BCD-Xyzv11a1bcde [HTTP: 200] - 0.157s - HelloWorldStack-helloworldfunction111A2BCD-Xyzv11a1bcde - 0.169s - Initialization - 0.058s - Invocation - 0.055s - ## index.handler - 0.000s - ### MySubSegment - 0.099s - Overhead
  13. 這是可透過網際網路存取的公有 API 端點。建議您在測試後刪除端點。

    cdk destroy

解讀 X-Ray 追蹤

設定主動追蹤之後,您可以透過應用程式來觀察特定請求。X-Ray 追蹤地圖提供了有關應用程式及其所有元件的資訊。下列範例顯示範例應用程式的追蹤:

範例應用程式的 X-Ray 服務映射