추적 TypeScript 코드 입력 AWS Lambda - AWS Lambda

추적 TypeScript 코드 입력 AWS Lambda

Lambda는 AWS X-Ray와 통합되어 Lambda 애플리케이션을 추적, 디버깅 및 최적화할 수 있습니다. Lambda 함수와 기타 AWS 서비스를 포함할 수 있는 애플리케이션의 리소스를 탐색할 때 X-Ray를 사용하여 요청을 추적할 수 있습니다.

추적 데이터를 X-Ray로 전송하려면 다음 세 SDK 라이브러리 중 하나를 사용할 수 있습니다.

각 SDK는 텔레메트리 데이터를 X-Ray 서비스로 전송하는 방법을 제공합니다. X-Ray를 사용하여 애플리케이션의 성능 지표를 확인하고, 필터링하고, 인사이트를 얻어 문제와 최적화 기회를 식별할 수 있습니다.

중요

X-Ray와 Powertools for AWS Lambda SDK는 AWS에서 제공하는 긴밀하게 통합된 계측 솔루션의 일부입니다. ADOT Lambda Layer는 일반적으로 더 많은 데이터를 수집하는 추적 계측기에 대한 전체 업계 표준의 일부이지만 모든 사용 사례에 적합하지는 않을 수 있습니다. 두 솔루션 중 하나를 사용하여 X-Ray에서 end-to-end 추적을 구현할 수 있습니다. 둘 중 하나를 선택하는 방법에 대해 자세히 알아보려면 AWS Distro for Open Telemetry와 X-Ray SDK 중에서 선택하기를 참조하세요.

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를 사용합니다.

아래 단계에 따라 를 사용하여 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 디렉터리를 엽니다. .ts라는 파일이 보일 것입니다. hello-world-stack 이 디렉터리에 hello-world.function.tshello-world.ts하는 2개의 새 파일을 만듭니다.

  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를 열고 파일에 다음 코드를 추가합니다. 여기에는 Lambda 함수를 생성하고, Powertools의 환경 변수를 NodejsFunction 구성하고, 로그 보존을 1주로 설정하는 구조가 포함되어 있습니다. 또한 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 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 서비스 맵