正在追踪 TypeScript 代码 AWS Lambda - AWS Lambda

正在追踪 TypeScript 代码 AWS Lambda

Lambda 与 AWS X-Ray 集成,以帮助您跟踪、调试和优化 Lambda 应用程序。您可以在某个请求遍历应用程序中的资源(其中可能包括 Lambda 函数和其他 AWS 服务)时,使用 X-Ray 跟踪该请求。

要将跟踪数据发送到 X-Ray,您可以使用以下三个开发工具包库之一:

每个开发工具包均提供了将遥测数据发送到 X-Ray 服务的方法。然后,您可以使用 X-Ray 查看、筛选和获得对应用程序性能指标的洞察,从而发现问题和优化机会。

重要

X-Ray 和 Powertools for AWS Lambda SDK 是 AWS 提供的紧密集成的分析解决方案的一部分。ADOT Lambda Layers 是全行业通用的跟踪分析标准的一部分,该标准通常会收集更多数据,但可能不适用于所有使用案例。您可以使用任一解决方案在 X-Ray 中实现 end-to-end 跟踪。要了解有关如何在两者之间进行选择的更多信息,请参阅在 AWS Distro for Open Telemetry 和 X-Ray 开发工具包之间进行选择

使用 Powertools AWS Lambda 进行 (TypeScript) 和AWS SAM追踪

按照以下步骤下载、构建和部署带有集成的 Powertools for AWS Lambda (TypeScript) 模块的 Hello World 示例 TypeScript 应用程序。AWS SAM此应用程序实现了基本的 API 后端,并使用 Powertools 发送日志、指标和跟踪。它由 Amazon API Gateway 端点和 Lambda 函数组成。当您向 API Gateway 终端节点发送 GET 请求时,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 traces

    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 采样率。

使用 Powertools AWS Lambda 进行 (TypeScript),使用来AWS CDK追踪

按照以下步骤下载、构建和部署带有集成的 Powertools for AWS Lambda (TypeScript) 模块的 Hello World 示例 TypeScript 应用程序。AWS CDK此应用程序实现了基本的 API 后端,并使用 Powertools 发送日志、指标和跟踪。它由 Amazon API Gateway 端点和 Lambda 函数组成。当您向 API Gateway 终端节点发送 GET 请求时,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 配置环境变量,并将日志保留时间设置为一周。它还包括用于创建 REST API 的LambdaRestApi 构造

    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 traces

    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 服务映射