Lambda 与 AWS X-Ray 集成,以帮助您跟踪、调试和优化 Lambda 应用程序。您可以在某个请求遍历应用程序中的资源(其中可能包括 Lambda 函数和其他 AWS 服务)时,使用 X-Ray 跟踪该请求。
要将跟踪数据发送到 X-Ray,您可以使用以下三个开发工具包库之一:
-
适用于 OpenTelemetry 的 AWS 发行版 (ADOT)
– 一种安全、可供生产、支持 AWS 的 OpenTelemetry (OTel) SDK 的分发版本。 -
适用于 Node.js 的 AWS X-Ray SDK – 用于生成跟踪数据并将其发送到 X-Ray 的 SDK。
-
Powertools for AWS Lambda(TypeScript)
– 一个开发人员工具包,可用于实施无服务器最佳实践并提高开发人员速度。
每个开发工具包均提供了将遥测数据发送到 X-Ray 服务的方法。然后,您可以使用 X-Ray 查看、筛选和获得对应用程序性能指标的洞察,从而发现问题和优化机会。
重要
X-Ray 和 Powertools for AWS Lambda SDK 是 AWS 提供的紧密集成的分析解决方案的一部分。ADOT Lambda Layers 是全行业通用的跟踪分析标准的一部分,该标准通常会收集更多数据,但可能不适用于所有使用案例。您可以使用任一解决方案在 X-Ray 中实现端到端跟踪。要了解有关如何在两者之间进行选择的更多信息,请参阅在 AWS Distro for Open Telemetry 和 X-Ray 开发工具包之间进行选择。
Sections
将 Powertools for AWS Lambda(TypeScript)和 AWS SAM 用于跟踪
请按照以下步骤使用 AWS SAM 通过集成的 Powertools for AWS Lambda(TypeScript)hello world
消息。
先决条件
要完成本节中的步骤,您必须满足以下条件:
-
Node.js 18.x 或更高版本
-
AWS SAM CLI 版本 1.75 或更高版本。如果您使用的是旧版本的 AWS SAM CLI,请参阅升级 AWS SAM CLI。
部署示例 AWS SAM 应用程序
-
使用 Hello World TypeScript 模板初始化该应用程序。
sam init --app-template hello-world-powertools-typescript --name sam-app --package-type Zip --runtime nodejs18.x --no-tracing
-
构建应用程序。
cd sam-app && sam build
-
部署应用程序。
sam deploy --guided
-
按照屏幕上的提示操作。要在交互式体验中接受提供的默认选项,请按
Enter
。注意
对于 HelloWorldFunction 可能没有定义授权,确定执行此操作吗?,确保输入
y
。 -
获取已部署应用程序的 URL:
aws cloudformation describe-stacks --stack-name sam-app --query 'Stacks[0].Outputs[?OutputKey==`HelloWorldApi`].OutputValue' --output text
-
调用 API 端点:
curl
<URL_FROM_PREVIOUS_STEP>
如果成功,您将会看到如下响应:
{"message":"hello world"}
-
要获取该函数的跟踪信息,请运行 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
-
这是一个可以通过互联网访问的公有 API 端点。我们建议您在测试后删除该端点。
sam delete
X-Ray 无法跟踪对应用程序的所有请求。X-Ray 将应用采样算法确保跟踪有效,同时仍会提供所有请求的一个代表性样本。采样率是每秒 1 个请求和 5% 的其他请求。您无法为函数配置此 X-Ray 采样率。
将 Powertools for AWS Lambda(TypeScript)和 AWS CDK 用于跟踪
请按照以下步骤使用 AWS CDK 通过集成的 Powertools for AWS Lambda(TypeScript)hello world
消息。
先决条件
要完成本节中的步骤,您必须满足以下条件:
-
Node.js 18.x 或更高版本
-
AWS SAM CLI 版本 1.75 或更高版本。如果您使用的是旧版本的 AWS SAM CLI,请参阅升级 AWS SAM CLI。
部署示例 AWS Cloud Development Kit (AWS CDK) 应用程序
-
为您的新应用程序创建一个项目目录。
mkdir hello-world cd hello-world
-
初始化该应用程序。
cdk init app --language typescript
-
添加 @types/aws-lambda
软件包作为开发依赖项。 npm install -D @types/aws-lambda
-
安装 Powertools Tracer 实用程序
。 npm install @aws-lambda-powertools/tracer
-
打开 lib 目录。您应该会看到一个名为 hello-world-stack.ts 的文件。在此目录中创建两个新文件:hello-world.function.ts 和 hello-world.ts。
-
打开 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; };
-
打开 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, }); } }
-
打开 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'); } }
-
部署您的应用程序。
cd .. cdk deploy
-
获取已部署应用程序的 URL:
aws cloudformation describe-stacks --stack-name HelloWorldStack --query 'Stacks[0].Outputs[?ExportName==`apiUrl`].OutputValue' --output text
-
调用 API 端点:
curl
<URL_FROM_PREVIOUS_STEP>
如果成功,您将会看到如下响应:
{"message":"hello world"}
-
要获取该函数的跟踪信息,请运行 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
-
这是一个可以通过互联网访问的公有 API 端点。我们建议您在测试后删除该端点。
cdk destroy
解释 X-Ray 跟踪
在配置活跃跟踪后,您可以通过应用程序观察特定请求。X-Ray 跟踪图将显示有关应用程序及其所有组件的信息。以下示例显示了一个示例应用程序的跟踪:
