

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

# 使用 監控無伺服器應用程式 AWS SAM
<a name="serverless-monitoring"></a>

部署無伺服器應用程式之後，您可以對其進行監控，以提供有關其操作的洞察並偵測異常，這有助於進行故障診斷。本節提供監控無伺服器應用程式的詳細資訊。這包括如何設定 Amazon CloudWatch 在偵測到異常時通知您的資訊。它還提供使用日誌的資訊，包括錯誤反白和檢視、篩選、擷取和結尾日誌的提示。

**Topics**
+ [使用 CloudWatch Application Insights 監控無 AWS SAM 伺服器應用程式](monitor-app-insights.md)
+ [在 中使用 日誌 AWS SAM](serverless-sam-cli-logging.md)

# 使用 CloudWatch Application Insights 監控無 AWS SAM 伺服器應用程式
<a name="monitor-app-insights"></a>

 Amazon CloudWatch Application Insights 可協助您監控應用程式中 AWS 的資源，以協助識別潛在問題。它可以分析 AWS 資源資料是否有問題的跡象，並建置自動化儀表板以視覺化它們。您可以設定 CloudWatch Application Insights 搭配您的 AWS Serverless Application Model (AWS SAM) 應用程式使用。若要進一步了解 CloudWatch Application Insights，請參閱《[Amazon CloudWatch 使用者指南》中的 Amazon CloudWatch Application Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html)。 *Amazon CloudWatch * 

**Topics**
+ [使用 設定 CloudWatch Application Insights AWS SAM](#monitor-app-insights-configure)
+ [後續步驟](#monitor-app-insights-next)

## 使用 設定 CloudWatch Application Insights AWS SAM
<a name="monitor-app-insights-configure"></a>

 透過 AWS SAM 命令列界面 (AWS SAM CLI) 或透過 AWS SAM 範本為您的 AWS SAM 應用程式設定 CloudWatch Application Insights。

### 透過 設定 AWS SAM CLI
<a name="monitor-app-insights-configure-cli"></a>

 使用 初始化應用程式時**sam init**，請透過互動式流程或使用 **--application-insights**選項來啟用 CloudWatch Application Insights。

 若要透過 AWS SAM CLI互動式流程啟用 CloudWatch Application Insights，請在出現提示**y**時輸入 。

```
Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]:
```

 若要使用 **--application-insights**選項啟用 CloudWatch Application Insights，請執行下列動作。

```
sam init --application-insights
```

 若要進一步了解如何使用 **sam init**命令，請參閱 [sam init](sam-cli-command-reference-sam-init.md)。

### 透過 AWS SAM 範本設定
<a name="monitor-app-insights-configure-template"></a>

 在 AWS SAM 範本`AWS::ApplicationInsights::Application`中定義 `AWS::ResourceGroups::Group`和資源，以啟用 CloudWatch Application Insights。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31 
...
Resources:
  ApplicationResourceGroup:
    Type: AWS::ResourceGroups::Group
    Properties:
      Name:
        Fn::Join:
        - ''
        - - ApplicationInsights-SAM-
        - Ref: AWS::StackName
      ResourceQuery:
        Type: CLOUDFORMATION_STACK_1_0
  ApplicationInsightsMonitoring:
    Type: AWS::ApplicationInsights::Application
    Properties:
      ResourceGroupName:
        Fn::Join:
          - ''
          - - ApplicationInsights-SAM-
          - Ref: AWS::StackName
        AutoConfigurationEnabled: 'true'
    DependsOn: ApplicationResourceGroup
```
+  `AWS::ResourceGroups::Group` – 建立群組來組織您的 AWS 資源，以便一次管理和自動化大量資源上的任務。在這裡，您可以建立要與 CloudWatch Application Insights 搭配使用的資源群組。如需此資源類型的詳細資訊，請參閱*AWS CloudFormation 《 使用者指南*[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-resourcegroups-group.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-resourcegroups-group.html)》中的 。
+  `AWS::ApplicationInsights::Application` – 設定資源群組的 CloudWatch Application Insights。如需此資源類型的詳細資訊，請參閱*AWS CloudFormation 《 使用者指南*[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationinsights-application.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationinsights-application.html)》中的 。

 這兩個資源都會在應用程式部署 CloudFormation 時自動傳遞至 。您可以使用 AWS SAM 範本中的 CloudFormation 語法進一步設定 CloudWatch Application Insights。如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用 CloudFormation 範本](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/appinsights-cloudformation.html)。

 使用 **sam init --application-insights**命令時，這兩個資源都會在您的 AWS SAM 範本中自動產生。以下是產生範本的範例。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app-test
  
  Sample SAM Template for sam-app-test

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3
    MemorySize: 128

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

  ApplicationResourceGroup:
    Type: AWS::ResourceGroups::Group
    Properties:
      Name:
        Fn::Join:
        - ''
        - - ApplicationInsights-SAM-
        - Ref: AWS::StackName
      ResourceQuery:
      	Type: CLOUDFORMATION_STACK_1_0
  ApplicationInsightsMonitoring:
    Type: AWS::ApplicationInsights::Application
    Properties:
      ResourceGroupName:
        Fn::Join:
        - ''
        - - ApplicationInsights-SAM-
        - Ref: AWS::StackName
      AutoConfigurationEnabled: 'true'
    DependsOn: ApplicationResourceGroup
    
Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldApi:
    Description: API Gateway endpoint URL for Prod stage for Hello World function
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: Hello World Lambda Function ARN
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: Implicit IAM Role created for Hello World function
    Value: !GetAtt HelloWorldFunctionRole.Arn
```

## 後續步驟
<a name="monitor-app-insights-next"></a>

 設定 CloudWatch Application Insights 之後，請使用 **sam build**建置您的應用程式**sam deploy**和部署您的應用程式。所有 CloudWatch Application Insights 支援的資源都會設定為監控。
+  如需支援的資源清單，請參閱《*Amazon CloudWatch 使用者指南*》中的[支援日誌和指標](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/appinsights-logs-and-metrics.html)。
+  若要了解如何存取 CloudWatch Application Insights，請參閱《Amazon [ CloudWatch 使用者指南》中的存取 CloudWatch Application Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/appinsights-accessing.html)。 *Amazon CloudWatch * 

# 在 中使用 日誌 AWS SAM
<a name="serverless-sam-cli-logging"></a>

為了簡化故障診斷， AWS SAM CLI有一個名為 的命令`sam logs`。此命令可讓您從命令列擷取 Lambda 函數產生的日誌。

**注意**  
`sam logs` 命令適用於所有 AWS Lambda 函數，而不只是您部署使用的函數 AWS SAM。

## 依 CloudFormation 堆疊擷取日誌
<a name="serverless-logging-cfn"></a>

當您的函數是 CloudFormation 堆疊的一部分時，您可以使用函數的邏輯 ID 來擷取日誌：

```
sam logs -n HelloWorldFunction --stack-name mystack
```

## 依 Lambda 函數名稱擷取日誌
<a name="serverless-logging-function"></a>

或者，您可以使用函數的名稱來擷取日誌：

```
sam logs -n mystack-HelloWorldFunction-1FJ8PD
```

## 自訂日誌
<a name="serverless-logging-tail"></a>

新增 `--tail`選項以等待新的日誌，並在它們到達時看到它們。這在部署期間或當您疑難排解生產問題時很有用。

```
sam logs -n HelloWorldFunction --stack-name mystack --tail
```

## 檢視特定時間範圍的日誌
<a name="serverless-logging-time-range"></a>

您可以使用 `-s`和 `-e`選項來檢視特定時間範圍的日誌：

```
sam logs -n HelloWorldFunction --stack-name mystack -s '10min ago' -e '2min ago'
```

## 篩選日誌
<a name="serverless-logging-time-range"></a>

使用 `--filter`選項快速尋找符合日誌事件中詞彙、片語或值的日誌：

```
sam logs -n HelloWorldFunction --stack-name mystack --filter "error"
```

在輸出中， AWS SAM CLI會強調「錯誤」一詞的所有出現，讓您可以輕鬆地在日誌輸出中尋找篩選條件關鍵字。

## 反白顯示錯誤
<a name="serverless-logging-error-highlight"></a>

當您的 Lambda 函數當機或逾時時， AWS SAM CLI會以紅色反白顯示逾時訊息。這可協助您輕鬆尋找日誌輸出巨型串流內逾時的特定執行。

## JSON 美型列印
<a name="serverless-logging-error-highlight"></a>

如果您的日誌訊息列印 JSON 字串， AWS SAM CLI會自動列印 JSON，以協助您以視覺化方式剖析和了解 JSON。