

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

# 使用 Amazon CloudWatch Logs 監控 OpenSearch 日誌
<a name="createdomain-configure-slow-logs"></a>

Amazon OpenSearch Service 透過 Amazon CloudWatch Logs 公開以下 OpenSearch 日誌：
+ 錯誤日誌
+ [搜尋請求慢速日誌](https://opensearch.org/docs/latest/install-and-configure/configuring-opensearch/logs/#search-request-slow-logs)
+ [碎片慢速日誌](https://opensearch.org/docs/latest/install-and-configure/configuring-opensearch/logs/#shard-slow-logs)
+ [稽核日誌](audit-logs.md)

搜尋碎片慢速日誌、索引碎片慢速日誌和錯誤日誌對於疑難排解效能和穩定性問題非常有用。稽核日誌會追蹤使用者活動，以符合規範。所有日誌都預設為*停用*狀態。如果已啟用，則套用[標準 CloudWatch 定價](https://aws.amazon.com/cloudwatch/pricing/)。

**注意**  
錯誤日誌僅適用於 OpenSearch 和 Elasticsearch 5.1 版和更高版本。慢速日誌則適用於所有 OpenSearch 和 Elasticsearch 版本。

對於其日誌，OpenSearch 使用 [Apache Log4j 2](https://logging.apache.org/log4j/2.x/) 及其內建的日誌層級 (從最不嚴重到最嚴重)：`TRACE`、`DEBUG`、`INFO`、`WARN`、`ERROR` 和 `FATAL`。

如果啟用錯誤日誌，OpenSearch Service 會將 `WARN`、`ERROR` 和 `FATAL` 的日誌行發佈至 CloudWatch。OpenSearch Service 也會發佈 `DEBUG` 等級的幾個例外狀況，包括下列項目：
+ `org.opensearch.index.mapper.MapperParsingException`
+ `org.opensearch.index.query.QueryShardException`
+ `org.opensearch.action.search.SearchPhaseExecutionException`
+ `org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException`
+ `java.lang.IllegalArgumentException`

在許多情況下，錯誤日誌可以協助排除故障，包括：
+ Painless 指令碼編譯問題
+ 無效查詢
+ 索引問題
+ 快照故障
+ 索引狀態管理遷移失敗
**注意**  
並非所有錯誤都會在錯誤日誌中回報。

**注意**  
OpenSearch Service 不會記錄發生的所有錯誤。

**Topics**
+ [啟用日誌發佈 (主控台)](#createdomain-configure-slow-logs-console)
+ [啟用日誌發佈 (AWS CLI)](#createdomain-configure-slow-logs-cli)
+ [啟用日誌發佈 (AWS SDKs)](#createdomain-configure-slow-logs-sdk)
+ [啟用日誌發佈 (CloudFormation)](#createdomain-configure-slow-logs-cfn)
+ [設定搜尋請求慢速日誌閾值](#createdomain-configure-search-request-slow-logs)
+ [設定碎片慢速日誌閾值](#createdomain-configure-slow-logs-indices)
+ [測試慢速日誌](#createdomain-configure-slow-logs-testing)
+ [檢視日誌](#createdomain-configure-slow-logs-viewing)

## 啟用日誌發佈 (主控台)
<a name="createdomain-configure-slow-logs-console"></a>

OpenSearch Service 主控台是將日誌發佈到 CloudWatch 的最簡單方式。

**若要將日誌發佈到 CloudWatch (主控台)**

1. 前往 **https：**//[aws.amazon.com](https://aws.amazon.com/)。

1. 在 **Analytics** (分析) 下，選擇 **Amazon OpenSearch Service**。

1. 選取您要更新的網域。

1. 在 **Logs** (日誌) 索引標籤上，選取日誌類型，然後選擇 **Enable** (啟用)。

1. 建立新的 CloudWatch 日誌群組或選擇現有的日誌群組。
**注意**  
您若打算啟用多個日誌，建議發佈每一個到它自己的日誌群組。這個分隔有助於更輕鬆掃描日誌。

1. 選擇包含適當許可權的存取政策，或使用主控台提供的 JSON 建立政策：

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "es.amazonaws.com"
         },
         "Action": [
           "logs:PutLogEvents",
           "logs:CreateLogStream"
         ],
         "Resource": "arn:aws:logs:us-east-1:111122223333:log-group:cw_log_group_name:*"
       }
     ]
   }
   ```

------

   建議您新增 `aws:SourceAccount` 和 `aws:SourceArn` 條件索引鍵至政策，保護自己免受[混淆代理人問題](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html)的困擾。來源帳戶是網域的擁有者，且來源 ARN 是網域 ARN。您的網域必須位於服務軟體 R20211203 或更新版本上，才能新增這些條件索引鍵。

   例如，您可以將下列條件區塊新增至政策：

   ```
   "Condition": {
       "StringEquals": {
           "aws:SourceAccount": "account-id"
       },
       "ArnLike": {
           "aws:SourceArn": "arn:aws:es:region:account-id:domain/domain-name"
       }
   }
   ```
**重要**  
CloudWatch Logs 支援[各區域 10 個資源政策](https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutResourcePolicy.html)。如果您打算為數個 OpenSearch Service 網域啟用日誌，您應該建立和重複使用包含多個日誌群組的更廣泛政策，以避免達到此限制。如需更新政策的相關步驟，請參閱[啟用日誌發佈 (AWS CLI)](#createdomain-configure-slow-logs-cli)。

1. 選擇**啟用**。

   網域變更的狀態會從 **Active (作用中)** 變成 **Processing (處理)**。啟用日誌發佈之前，必須使狀態變回 **Active** (作用中)。這項變更通常需要 30 分鐘，但可能需要更長的時間，視您的網域組態而定。

如果您啟用其中一個碎片慢速日誌，請參閱 [設定碎片慢速日誌閾值](#createdomain-configure-slow-logs-indices)。如果啟用稽核日誌，請參閱[步驟 2：開啟 OpenSearch Dashboards 中的稽核日誌](audit-logs.md#audit-log-dashboards-ui)。如果您只啟用了錯誤日誌，則不需要執行任何其他設定步驟。

## 啟用日誌發佈 (AWS CLI)
<a name="createdomain-configure-slow-logs-cli"></a>

在啟用日誌發佈之前，您需要一個 CloudWatch 日誌群組。如果還沒有日誌群組，您可以使用下列命令建立一個：

```
aws logs create-log-group --log-group-name my-log-group
```

輸入下一個命令來尋找日誌群組的 ARN，然後*記下來*：

```
aws logs describe-log-groups --log-group-name my-log-group
```

現在您可以提供 OpenSearch Service 許可以寫入日誌群組。您接近命令最後，必須提供日誌群組的 ARN：

```
aws logs put-resource-policy \
  --policy-name my-policy \
  --policy-document '{ "Version": "2012-10-17",		 	 	  "Statement": [{ "Sid": "", "Effect": "Allow", "Principal": { "Service": "es.amazonaws.com"}, "Action":[ "logs:PutLogEvents","logs:CreateLogStream"],"Resource": "cw_log_group_arn:*"}]}'
```

**重要**  
CloudWatch Logs 支援[各區域 10 個資源政策](https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutResourcePolicy.html)。如果您計劃為數個 OpenSearch Service 網域啟用碎片慢速日誌，您應該建立並重複使用更廣泛的政策，其中包含多個日誌群組，以避免達到此限制。

如果您稍後需要檢閱此政策，請使用 `aws logs describe-resource-policies` 命令。若要更新此政策，請使用新的政策文件發出相同的 `aws logs put-resource-policy` 命令。

最後，您可以使用 `--log-publishing-options` 選項，以啟用發佈。選項的語法對於 `create-domain` 和 `update-domain-config` 命令都是相同的。

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/createdomain-configure-slow-logs.html)

**注意**  
您若打算啟用多個日誌，建議發佈每一個到它自己的日誌群組。這個分隔有助於更輕鬆掃描日誌。

**範例**

下列範例會啟用發佈指定網域的搜尋和索引碎片慢速日誌：

```
aws opensearch update-domain-config \
  --domain-name my-domain \
  --log-publishing-options "SEARCH_SLOW_LOGS={CloudWatchLogsLogGroupArn=arn:aws:logs:us-east-1:123456789012:log-group:my-log-group,Enabled=true},INDEX_SLOW_LOGS={CloudWatchLogsLogGroupArn=arn:aws:logs:us-east-1:123456789012:log-group:my-other-log-group,Enabled=true}"
```

若要停用發佈到 CloudWatch，可使用 `Enabled=false` 執行相同命令。

如果您啟用其中一個碎片慢速日誌，請參閱 [設定碎片慢速日誌閾值](#createdomain-configure-slow-logs-indices)。如果啟用稽核日誌，請參閱[步驟 2：開啟 OpenSearch Dashboards 中的稽核日誌](audit-logs.md#audit-log-dashboards-ui)。如果您只啟用了錯誤日誌，則不需要執行任何其他設定步驟。

## 啟用日誌發佈 (AWS SDKs)
<a name="createdomain-configure-slow-logs-sdk"></a>

在可以啟用日誌發佈之前，必須先建立一個 CloudWatch 日誌群組，取得其 ARN，並提供 OpenSearch Service 許可以寫入到其中。相關的操作全記錄在 [Amazon CloudWatch Logs API 參考](https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/)中：
+ `CreateLogGroup`
+ `DescribeLogGroup`
+ `PutResourcePolicy`

您可以使用 [AWS 開發套件](https://aws.amazon.com/tools/#sdk)存取這些操作。

 AWS SDKs(Android 和 iOS SDKs除外） 支援 [Amazon OpenSearch Service API 參考](https://docs.aws.amazon.com/opensearch-service/latest/APIReference/Welcome.html)中定義的所有操作，包括 `CreateDomain`和 `--log-publishing-options`的選項`UpdateDomainConfig`。

如果您啟用其中一個碎片慢速日誌，請參閱 [設定碎片慢速日誌閾值](#createdomain-configure-slow-logs-indices)。如果您只啟用了錯誤日誌，則不需要執行任何其他設定步驟。

## 啟用日誌發佈 (CloudFormation)
<a name="createdomain-configure-slow-logs-cfn"></a>

在此範例中，我們使用 CloudFormation 建立名為 的日誌群組`opensearch-logs`、指派適當的許可，然後建立已啟用應用程式日誌的日誌發佈、搜尋碎片慢速日誌和索引慢速日誌的網域。

在啟用日誌發佈之前，您需要建立 CloudWatch 日誌群組︰

```
Resources:
  OpenSearchLogGroup:
    Type: AWS::Logs::LogGroup
    Properties: 
      LogGroupName: opensearch-logs
Outputs:
  Arn:
    Value:
      'Fn::GetAtt':
        - OpenSearchLogGroup
        - Arn
```

範本輸出日誌群組的 ARN。在本案例中，ARN 為 `arn:aws:logs:us-east-1:123456789012:log-group:opensearch-logs`。

使用 ARN 會建立一項資源政策，賦予 OpenSearch Service 許可以寫入日誌群組：

```
Resources:
 OpenSearchLogPolicy:
   Type: AWS::Logs::ResourcePolicy
   Properties:
     PolicyName: my-policy
     PolicyDocument: "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Sid\": \"\", \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"es.amazonaws.com\"}, \"Action\":[ \"logs:PutLogEvents\",\"logs:CreateLogStream\"],\"Resource\": \"arn:aws:logs:us-east-1:123456789012:log-group:opensearch-logs:*\"}]}"
```

最後，建立以下 CloudFormation 堆疊，其會產生已啟用日誌發佈的 OpenSearch Service 網域。存取政策允許使用者 AWS 帳戶 讓 向網域提出所有 HTTP 請求。

```
Resources:
  OpenSearchServiceDomain:
    Type: "AWS::OpenSearchService::Domain"
    Properties:
      DomainName: my-domain
      EngineVersion: "OpenSearch_1.0"
      ClusterConfig:
        InstanceCount: 2
        InstanceType: "r6g.xlarge.search"
        DedicatedMasterEnabled: true
        DedicatedMasterCount: 3
        DedicatedMasterType: "r6g.xlarge.search"
      EBSOptions:
        EBSEnabled: true
        VolumeSize: 10
        VolumeType: "gp2"
      AccessPolicies:
        Version: "2012-10-17"		 	 	 
        Statement:
            Effect: "Allow"
            Principal:
                AWS: "arn:aws:iam::123456789012:user/es-user"
            Action: "es:*"
            Resource: "arn:aws:es:us-east-1:123456789012:domain/my-domain/*"
      LogPublishingOptions:
        ES_APPLICATION_LOGS:
          CloudWatchLogsLogGroupArn: "arn:aws:logs:us-east-1:123456789012:log-group:opensearch-logs"
          Enabled: true
        SEARCH_SLOW_LOGS:
          CloudWatchLogsLogGroupArn: "arn:aws:logs:us-east-1:123456789012:log-group:opensearch-logs"
          Enabled: true
        INDEX_SLOW_LOGS:
          CloudWatchLogsLogGroupArn: "arn:aws:logs:us-east-1:123456789012:log-group:opensearch-logs"
          Enabled: true
```

如需詳細的語法資訊，請參閱 *CloudFormation 使用者指南*中的[日誌發佈選項](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-logpublishingoption.html)。

## 設定搜尋請求慢速日誌閾值
<a name="createdomain-configure-search-request-slow-logs"></a>

[搜尋請求慢速日誌](https://opensearch.org/docs/latest/install-and-configure/configuring-opensearch/logs/#search-request-slow-logs)可用於搜尋在 2.13 版和更新版本上執行的 OpenSearch Service 網域。搜尋請求慢速日誌閾值會針對總請求花費時間進行設定。這與針對個別碎片所花費時間設定的碎片請求慢速日誌不同。

您可以使用叢集設定指定搜尋請求慢速日誌。這與您使用索引設定啟用的碎片慢速日誌不同。例如，您可以透過 OpenSearch REST API 指定下列設定：

```
PUT domain-endpoint/_cluster/settings
{
  "transient": {
    "cluster.search.request.slowlog.threshold.warn": "5s",
    "cluster.search.request.slowlog.threshold.info": "2s"
  }
}
```

**注意**  
`PUT /_cluster/settings` 端點在 Amazon OpenSearch Service 中受到限制。傳送此請求將傳回錯誤：`Your request: '/_cluster/settings' payload is not allowed.`若要設定碎片慢速日誌閾值，請改用索引層級設定。例如：  

```
PUT domain-endpoint/index/_settings
{
  "index.search.slowlog.threshold.query.warn": "5s",
  "index.search.slowlog.threshold.query.info": "2s"
}
```

## 設定碎片慢速日誌閾值
<a name="createdomain-configure-slow-logs-indices"></a>

OpenSearch 預設會停用[碎片慢速日誌](https://opensearch.org/docs/latest/install-and-configure/configuring-opensearch/logs/#shard-slow-logs)。啟用碎片慢速日誌*發佈*至 CloudWatch 之後，您仍然必須為每個 OpenSearch 索引指定記錄閾值。這些閾值精確定義該記錄哪些內容、日誌層級為何等等。

例如，您可以透過 OpenSearch REST API 指定這些設定：

```
PUT domain-endpoint/index/_settings
{
  "index.search.slowlog.threshold.query.warn": "5s",
  "index.search.slowlog.threshold.query.info": "2s"
}
```

## 測試慢速日誌
<a name="createdomain-configure-slow-logs-testing"></a>

若要測試搜尋請求和碎片慢速日誌是否皆成功發佈，請考慮從非常低的值開始，以驗證日誌是否出現在 CloudWatch 中，然後將閾值提高到更有用的層級。

如果日誌未出現，請檢查下列各項：
+ CloudWatch 日誌群組是否存在？ 檢查 CloudWatch 主控台。
+ OpenSearch Service 是否擁有寫入到日誌群組的許可？ 檢查 OpenSearch Service 主控台。
+ OpenSearch Service 網域是否設定為發佈到日誌群組？ 檢查 OpenSearch Service 主控台、使用 AWS CLI `describe-domain-config`選項，或使用`DescribeDomainConfig`其中一個 SDKs呼叫 。
+ OpenSearch 記錄閾值是否低到您的請求超出它們？ 

  若要檢閱網域的搜尋請求慢速日誌閾值，請使用下列命令：

  ```
  GET domain-endpoint/_cluster/settings?flat_settings
  ```

  若要檢閱索引的碎片慢速日誌閾值，請使用下列命令：

  ```
  GET domain-endpoint/index/_settings?pretty
  ```

如果您想要停用索引的慢速日誌，請傳回變更為其預設值 `-1` 的任何閾值。

使用 OpenSearch Service 主控台停用發佈至 CloudWatch，或 AWS CLI *不會*停止 OpenSearch 產生日誌；只會停止*發佈*這些日誌。如果您不再需要碎片慢速日誌，請務必檢查您的索引設定；如果您不再需要搜尋請求慢速日誌，請務必檢查您的網域設定。

## 檢視日誌
<a name="createdomain-configure-slow-logs-viewing"></a>

檢視 CloudWatch 中的應用程式和慢速日誌，就像檢視其他任何 CloudWatch 日誌一樣。如需詳細資訊，請參閱 *Amazon CloudWatch Logs 使用者指南*中的[檢視日誌資料](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#ViewingLogData)。

以下是檢視日誌的一些考量事項：
+ OpenSearch Service 只發佈每一行的前 255,000 個字元到 CloudWatch。任何剩餘內容會被截斷。對於稽核日誌，每個訊息為 10,000 個字元。
+ 在 CloudWatch 中，日誌串流名稱的尾碼 `-index-slow-logs`、`-search-slow-logs`、`-application-logs` 和 `-audit-logs` 有助於識別其內容。