

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

# 記錄和監控 TypeScript Lambda 函數
<a name="typescript-logging"></a>

AWS Lambda 會自動監控 Lambda 函數，並將日誌項目傳送至 Amazon CloudWatch。您的 Lambda 函數隨附有 CloudWatch Logs 日誌群組，且函數的每一執行個體各有一個日誌串流。Lambda 執行期環境會將每次調用的詳細資訊和函數程式碼的其他輸出，傳送至日誌串流。如需 CloudWatch Logs 的詳細資訊，請參閱[將 Lambda 函式日誌傳送至 CloudWatch Logs](monitoring-cloudwatchlogs.md)。

若要由您的函數程式碼輸出日誌，您可以在[主控台物件](https://nodejs.org/docs/latest-v18.x/api/console.html)上使用方法。若要更詳細記錄，您可以使用任何寫入 `stdout` 或 `stderr` 的記錄程式庫。

**Topics**
+ [使用日誌記錄工具和程式庫](#typescript-tools-libraries)
+ [使用 Powertools for AWS Lambda (TypeScript) 和 AWS SAM 進行結構化記錄](#typescript-logging-sam)
+ [使用 Powertools for AWS Lambda (TypeScript) 和 AWS CDK 進行結構化記錄](#typescript-logging-cdk)
+ [在 Lambda 主控台檢視日誌](#typescript-logging-console)
+ [在 CloudWatch 主控台中檢視 記錄](#typescript-logging-cwconsole)

## 使用日誌記錄工具和程式庫
<a name="typescript-tools-libraries"></a>

[Powertools for AWS Lambda (TypeScript)](https://docs.aws.amazon.com/powertools/typescript/) 是一種開發人員工具組，可實作無伺服器最佳實務並提高開發人員速度。[Logger 公用程式](https://docs.powertools.aws.dev/lambda/typescript/latest/features/logger/)提供 Lambda 優化記錄器，其中包含有關所有函數之函數內容的其他資訊，輸出結構為 JSON。使用此公用程式執行下列操作：
+ 從 Lambda 內容、冷啟動和 JSON 形式的結構記錄輸出中擷取關鍵欄位
+ 在收到指示時記錄 Lambda 調用事件 (預設為停用)
+ 透過日誌採樣僅列印調用百分比的所有日誌 (預設為停用)
+ 在任何時間點將其他金鑰附加至結構化日誌
+ 使用自訂日誌格式化程式 (自帶格式化程式)，以與組織的日誌記錄 RFC 相容的結構輸出日誌。

## 使用 Powertools for AWS Lambda (TypeScript) 和 AWS SAM 進行結構化記錄
<a name="typescript-logging-sam"></a>

請依照下列步驟，使用 搭配整合式 Powertools for (TypeScript) 模組下載、建置和部署範例 Hello World TypeScript 應用程式 AWS SAM。 [AWS Lambda TypeScript](https://docs.powertools.aws.dev/lambda-typescript) 此應用程式實作了基本 API 後端，並使用 Powertools 發送日誌、指標和追蹤。其包含 Amazon API Gateway 端點和 Lambda 函數。當您將 GET 請求傳送至 API Gateway 端點時，Lambda 函數會調用、使用內嵌指標格式將日誌和指標傳送至 CloudWatch，並將追蹤傳送至 AWS X-Ray。該函數會傳回 `hello world` 訊息。

**先決條件**

若要完成本節中的步驟，您必須執行下列各項：
+ Node.js 20 或更新版本
+ [AWS CLI 第 2 版](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ [AWS SAM CLI 1.75 版或更新版本。](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)如果您有較舊版本的 AWS SAM CLI，請參閱[升級 AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/manage-sam-cli-versions.html#manage-sam-cli-versions-upgrade)。

**部署範例 AWS SAM 應用程式**

1. 使用 Hello World TypeScript 範本來初始化應用程式。

   ```
   sam init --app-template hello-world-powertools-typescript --name sam-app --package-type Zip --runtime nodejs24.x
   ```

1. 建置應用程式。

   ```
   cd sam-app && sam build
   ```

1. 部署應用程式。

   ```
   sam deploy --guided
   ```

1. 依照螢幕上的提示操作。若要接受互動體驗中提供的預設選項，請按下 `Enter`。
**注意**  
對於 **HelloWorldFunction may not have authorization defined, Is this okay?**，確保輸入 `y`。

1. 取得已部署應用程式的 URL：

   ```
   aws cloudformation describe-stacks --stack-name sam-app --query 'Stacks[0].Outputs[?OutputKey==`HelloWorldApi`].OutputValue' --output text
   ```

1. 調用 API 端點：

   ```
   curl <URL_FROM_PREVIOUS_STEP>
   ```

   成功的話，您將會看到以下回應：

   ```
   {"message":"hello world"}
   ```

1. 若要獲取該函數的日誌，請執行 [sam 日誌](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-logs.html)。如需詳細資訊，請參閱《AWS Serverless Application Model 開發人員指南》** 中的 [使用日誌](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html)。

   ```
   sam logs --stack-name sam-app
   ```

   日誌輸出如下：

   ```
   2025/01/31/[$LATEST]4d53e8d279824834a1ccd35511a4949c 2025-08-31T09:33:10.552000 START RequestId: 70693159-7e94-4102-a2af-98a6343fb8fb Version: $LATEST
   2025/01/31/[$LATEST]4d53e8d279824834a1ccd35511a4949c 2025-08-31T09:33:10.594000 2025-08-31T09:33:10.557Z 70693159-7e94-4102-a2af-98a6343fb8fb INFO {"_aws":{"Timestamp":1661938390556,"CloudWatchMetrics":[{"Namespace":"sam-app","Dimensions":[["service"]],"Metrics":[{"Name":"ColdStart","Unit":"Count"}]}]},"service":"helloWorld","ColdStart":1}
   2025/01/31/[$LATEST]4d53e8d279824834a1ccd35511a4949c 2025-08-31T09:33:10.595000 2025-08-31T09:33:10.595Z 70693159-7e94-4102-a2af-98a6343fb8fb INFO {"level":"INFO","message":"This is an INFO log - sending HTTP 200 - hello world response","service":"helloWorld","timestamp":"2025-08-31T09:33:10.594Z"}
   2025/01/31/[$LATEST]4d53e8d279824834a1ccd35511a4949c 2025-08-31T09:33:10.655000 2025-08-31T09:33:10.655Z 70693159-7e94-4102-a2af-98a6343fb8fb INFO {"_aws":{"Timestamp":1661938390655,"CloudWatchMetrics":[{"Namespace":"sam-app","Dimensions":[["service"]],"Metrics":[]}]},"service":"helloWorld"}
   2025/01/31/[$LATEST]4d53e8d279824834a1ccd35511a4949c 2025-08-31T09:33:10.754000 END RequestId: 70693159-7e94-4102-a2af-98a6343fb8fb
   2025/01/31/[$LATEST]4d53e8d279824834a1ccd35511a4949c 2025-08-31T09:33:10.754000 REPORT RequestId: 70693159-7e94-4102-a2af-98a6343fb8fb Duration: 201.55 ms Billed Duration: 202 ms Memory Size: 128 MB Max Memory Used: 66 MB Init Duration: 252.42 ms
   XRAY TraceId: 1-630f2ad5-1de22b6d29a658a466e7ecf5 SegmentId: 567c116658fbf11a Sampled: true
   ```

1. 這是可透過網際網路存取的公有 API 端點。建議您在測試後刪除端點。

   ```
   sam delete
   ```

### 管理日誌保留
<a name="typescript-log-retention"></a>

當您刪除函數時，不會自動刪除日誌群組。若要避免無限期地儲存日誌，請刪除日誌群組，或設定保留期間，CloudWatch 會在該時間之後自動刪除日誌。若要設定日誌保留，請將下列項目新增至您的 AWS SAM 範本：

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
    # Omitting other properties
  
  LogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub "/aws/lambda/${HelloWorldFunction}"
      RetentionInDays: 7
```

## 使用 Powertools for AWS Lambda (TypeScript) 和 AWS CDK 進行結構化記錄
<a name="typescript-logging-cdk"></a>

請依照下列步驟，使用 下載、建置和部署範例 Hello World TypeScript 應用程式，搭配整合式 [Powertools for AWS Lambda (TypeScript)](https://docs.powertools.aws.dev/lambda-typescript) 模組 AWS CDK。此應用程式實作了基本 API 後端，並使用 Powertools 發送日誌、指標和追蹤。其包含 Amazon API Gateway 端點和 Lambda 函數。當您將 GET 請求傳送至 API Gateway 端點時，Lambda 函數會調用、使用內嵌指標格式將日誌和指標傳送至 CloudWatch，並將追蹤傳送至 AWS X-Ray。該函數會傳回 `hello world` 訊息。

**先決條件**

若要完成本節中的步驟，您必須執行下列各項：
+ Node.js 20 或更新版本
+ [AWS CLI 第 2 版](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ [AWS CDK 第 2 版](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_prerequisites)
+ [AWS SAM CLI 1.75 版或更新版本。](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)如果您有較舊版本的 AWS SAM CLI，請參閱[升級 AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/manage-sam-cli-versions.html#manage-sam-cli-versions-upgrade)。

**部署範例 AWS CDK 應用程式**

1. 為您的新應用程式建立專案目錄。

   ```
   mkdir hello-world
   cd hello-world
   ```

1. 初始化應用程式。

   ```
   cdk init app --language typescript
   ```

1. 新增 [@types/aws-lambda](https://www.npmjs.com/package/@types/aws-lambda) 套件作為開發相依項。

   ```
   npm install -D @types/aws-lambda
   ```

1. 安裝 Powertools [Logger 公用程式](https://docs.aws.amazon.com/powertools/typescript/latest/features/logger/)。

   ```
   npm install @aws-lambda-powertools/logger
   ```

1. 開啟 **lib** 目錄。您應看到名稱為 **hello-world-stack.ts** 的檔案。在此目錄中建立兩個新檔案：**hello-world.function.ts** 和 **hello-world.ts**。

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

   ```
   import { APIGatewayEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
   import { Logger } from '@aws-lambda-powertools/logger';
   const logger = new Logger();
     
   export const handler = async (event: APIGatewayEvent, context: Context): Promise<APIGatewayProxyResult> => {
     logger.info('This is an INFO log - sending HTTP 200 - hello world response');
     return {
       statusCode: 200,
       body: JSON.stringify({
         message: 'hello world',
       }),
     };
   };
   ```

1. 開啟 **hello-world.ts**，然後將下列程式碼新增至檔案。其中包含 [NodejsFunction 建構模組](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs-readme.html)，它會建立 Lambda 函數、設定 Powertools 的環境變數，並將日誌保留設定為一週。另外也包括負責建立 REST API 的 [LambdaRestApi 建構模組](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.LambdaRestApi.html)。

   ```
   import { Construct } from 'constructs';
   import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
   import { LambdaRestApi } from 'aws-cdk-lib/aws-apigateway';
   import { RetentionDays } from 'aws-cdk-lib/aws-logs';
   import { CfnOutput } from 'aws-cdk-lib';
     
   export class HelloWorld extends Construct {
     constructor(scope: Construct, id: string) {
       super(scope, id);
       const helloFunction = new NodejsFunction(this, 'function', {
         environment: {
           Powertools_SERVICE_NAME: 'helloWorld',
           LOG_LEVEL: 'INFO',
         },
         logRetention: RetentionDays.ONE_WEEK,
       });
       const api = new LambdaRestApi(this, 'apigw', {
         handler: helloFunction,
       });
       new CfnOutput(this, 'apiUrl', {
         exportName: 'apiUrl',
         value: api.url,
       });
     }
   }
   ```

1. 開啟 **hello-world-stack.ts**。這是定義 [AWS CDK 堆疊](https://docs.aws.amazon.com/cdk/v2/guide/stacks.html)的程式碼。將程式碼取代為以下內容：

   ```
   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');
     }
   }
   ```

1. 返回專案目錄。

   ```
   cd hello-world
   ```

1. 部署您的應用程式。

   ```
   cdk deploy
   ```

1. 取得已部署應用程式的 URL：

   ```
   aws cloudformation describe-stacks --stack-name HelloWorldStack --query 'Stacks[0].Outputs[?ExportName==`apiUrl`].OutputValue' --output text
   ```

1. 調用 API 端點：

   ```
   curl <URL_FROM_PREVIOUS_STEP>
   ```

   成功的話，您將會看到以下回應：

   ```
   {"message":"hello world"}
   ```

1. 若要獲取該函數的日誌，請執行 [sam 日誌](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-logs.html)。如需詳細資訊，請參閱《AWS Serverless Application Model 開發人員指南》** 中的 [使用日誌](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html)。

   ```
   sam logs --stack-name HelloWorldStack
   ```

   日誌輸出如下：

   ```
   2025/01/31/[$LATEST]2ca67f180dcd4d3e88b5d68576740c8e 2025-08-31T14:48:37.047000 START RequestId: 19ad1007-ff67-40ce-9afe-0af0a9eb512c Version: $LATEST
   2025/01/31/[$LATEST]2ca67f180dcd4d3e88b5d68576740c8e 2025-08-31T14:48:37.050000 {
   "level": "INFO",
   "message": "This is an INFO log - sending HTTP 200 - hello world response",
   "service": "helloWorld",
   "timestamp": "2025-08-31T14:48:37.048Z",
   "xray_trace_id": "1-630f74c4-2b080cf77680a04f2362bcf2"
   }
   2025/01/31/[$LATEST]2ca67f180dcd4d3e88b5d68576740c8e 2025-08-31T14:48:37.082000 END RequestId: 19ad1007-ff67-40ce-9afe-0af0a9eb512c
   2025/01/31/[$LATEST]2ca67f180dcd4d3e88b5d68576740c8e 2025-08-31T14:48:37.082000 REPORT RequestId: 19ad1007-ff67-40ce-9afe-0af0a9eb512c Duration: 34.60 ms Billed Duration: 35 ms Memory Size: 128 MB Max Memory Used: 57 MB Init Duration: 173.48 ms
   ```

1. 這是可透過網際網路存取的公有 API 端點。建議您在測試後刪除端點。

   ```
   cdk destroy
   ```

## 在 Lambda 主控台檢視日誌
<a name="typescript-logging-console"></a>

您可以在調用 Lambda 函數之後，使用 Lambda 主控台來檢視日誌輸出。

如果可以從內嵌**程式碼**編輯器測試您的程式碼，您會在**執行結果**中找到日誌。使用主控台測試功能以調用函數時，您會在**詳細資訊**區段找到**日誌輸出**。

## 在 CloudWatch 主控台中檢視 記錄
<a name="typescript-logging-cwconsole"></a>

您可以使用 Amazon CloudWatch 主控台來檢視所有 Lambda 函數調用的日誌。

**若要在 CloudWatch 主控台上檢視日誌**

1. 在 CloudWatch 主控台上開啟[日誌群組頁面](https://console.aws.amazon.com/cloudwatch/home?#logs:)。

1. 選擇您的函數的日誌群組 (**/aws/lambda/*your-function-name***)。

1. 選擇日誌串流

每個日誌串流都會對應至[函式的執行個體](lambda-runtime-environment.md)。當您更新 Lambda 函數，以及建立其他執行個體以處理並行調用時，就會顯示日誌串流。若要尋找特定調用的日誌，建議您使用 檢測函數 AWS X-Ray。X-Ray 會在追蹤內記錄有關請求和日誌串流的詳細資訊。