

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

# 查詢 Application Load Balancer 日誌
<a name="application-load-balancer-logs"></a>

Application Load Balancer 是 Elastic Load Balancing 的一個負載平衡選項，可實施使用容器的微服務部署中的流量分配。查詢 Application Load Balancer 日誌可讓您查看流量來源、延遲，以及往返於 Elastic Load Balancing 執行個體與後端應用程式傳輸的位元組。如需詳細資訊，請參閱《Application Load Balancer 使用者指南**》中的 [Application Load Balancer 的存取日誌](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html)和 [Application Load Balancer 的連線日誌](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-connection-logs.html)。

## 先決條件
<a name="application-load-balancer-logs-prerequisites"></a>
+ 啟用[存取日誌記錄](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html)或[連線日誌記錄](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-connection-logs.html)，以便 Application Load Balancer 日誌可以儲存到您的 Amazon S3 儲存貯體中。
+ 用於保存您將為 Athena 建立的資料表的資料庫。若要建立資料庫，您可以使用 Athena 或 AWS Glue 主控台。如需詳細資訊，請參閱本指南中的 [在 Athena 中建立資料庫](creating-databases.md)，或《 AWS 開發人員指南》[https://docs.aws.amazon.com/glue/latest/dg/console-databases.html](https://docs.aws.amazon.com/glue/latest/dg/console-databases.html)中的*在AWS Glue Glue 主控台上使用資料庫*。

**Topics**
+ [先決條件](#application-load-balancer-logs-prerequisites)
+ [建立 ALB 存取日誌的資料表](create-alb-access-logs-table.md)
+ [使用分割區投影在 Athena 中建立 ALB 存取日誌的資料表](create-alb-access-logs-table-partition-projection.md)
+ [ALB 存取日誌的查詢範例](query-alb-access-logs-examples.md)
+ [建立 ALB 連線日誌的資料表](create-alb-connection-logs-table.md)
+ [使用分割區投影在 Athena 中建立 ALB 連線日誌的資料表](create-alb-connection-logs-table-partition-projection.md)
+ [ALB 連線日誌的查詢範例](query-alb-connection-logs-examples.md)
+ [其他資源](application-load-balancer-logs-additional-resources.md)

# 建立 ALB 存取日誌的資料表
<a name="create-alb-access-logs-table"></a>

1. 複製下列 `CREATE TABLE` 陳述式，並將其貼到 Athena 主控台查詢編輯器，然後針對自己的日誌項目要求視需要進行修改。如需有關 Athena 主控台入門的資訊，請參閱[開始使用](getting-started.md)。將 `LOCATION` 子句中的路徑取代為您的 Amazon S3 存取日誌資料夾位置。如需有關存取日誌檔案位置的詳細資訊，請參閱《Application Load Balancer 使用者指南**》中的[存取日誌檔案](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#access-log-file-format)。

   如需有關每個日誌檔案欄位的資訊，請參閱《Application Load Balancer 使用者指南**》中的[存取日誌項目](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#access-log-entry-format)。
**注意**  
下列範例 `CREATE TABLE` 陳述式包含最近新增的 `classification`、`classification_reason` 和 `conn_trace_id` (「可追溯性 ID」或 TID) 資料欄。若要為不含這些項目的 Application Load Balancer 存取日誌建立資料表，請從 `CREATE TABLE` 陳述式移除相應的資料欄，然後據此修改規則表達式。

   ```
   CREATE EXTERNAL TABLE IF NOT EXISTS alb_access_logs (
               type string,
               time string,
               elb string,
               client_ip string,
               client_port int,
               target_ip string,
               target_port int,
               request_processing_time double,
               target_processing_time double,
               response_processing_time double,
               elb_status_code int,
               target_status_code string,
               received_bytes bigint,
               sent_bytes bigint,
               request_verb string,
               request_url string,
               request_proto string,
               user_agent string,
               ssl_cipher string,
               ssl_protocol string,
               target_group_arn string,
               trace_id string,
               domain_name string,
               chosen_cert_arn string,
               matched_rule_priority string,
               request_creation_time string,
               actions_executed string,
               redirect_url string,
               lambda_error_reason string,
               target_port_list string,
               target_status_code_list string,
               classification string,
               classification_reason string,
               conn_trace_id string
               )
               ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
               WITH SERDEPROPERTIES (
               'serialization.format' = '1',
               'input.regex' = 
           '([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*):([0-9]*) ([^ ]*)[:-]([0-9]*) ([-.0-9]*) ([-.0-9]*) ([-.0-9]*) (|[-0-9]*) (-|[-0-9]*) ([-0-9]*) ([-0-9]*) \"([^ ]*) (.*) (- |[^ ]*)\" \"([^\"]*)\" ([A-Z0-9-_]+) ([A-Za-z0-9.-]*) ([^ ]*) \"([^\"]*)\" \"([^\"]*)\" \"([^\"]*)\" ([-.0-9]*) ([^ ]*) \"([^\"]*)\" \"([^\"]*)\" \"([^ ]*)\" \"([^\\s]+?)\" \"([^\\s]+)\" \"([^ ]*)\" \"([^ ]*)\" ?([^ ]*)? ?( .*)?'
               )
               LOCATION 's3://amzn-s3-demo-bucket/access-log-folder-path/'
   ```
**注意**  
我們建議在 `input.regex` 參數的結尾一律保留模式 *`?( .*)?`*，以便在新增新的 ALB 日誌欄位時，處理未來的日誌項目。

1. 在 Athena 主控台中執行查詢。查詢完成之後，Athena 會註冊 `alb_access_logs` 資料表，讓其中的資料可供您發出查詢。

# 使用分割區投影在 Athena 中建立 ALB 存取日誌的資料表
<a name="create-alb-access-logs-table-partition-projection"></a>

由於 ALB 存取日誌具有您可以事先指定其分割區結構描述的已知結構，您可以使用 Athena 分割區投影功能減少查詢執行時期並自動化分割區管理。分割區投影會在新增資料時自動新增分割區。因此您無需使用 `ALTER TABLE ADD PARTITION` 手動新增分割區。

以下範例 `CREATE TABLE` 陳述式會從指定日期到現在，對單一 AWS 區域的 ALB 存取日誌自動使用分割區投影。該陳述式基於上一節中的範例，但新增了 `PARTITIONED BY` 和 `TBLPROPERTIES` 子句以啟用分割區投影。在 `LOCATION` 和 `storage.location.template` 子句中，請將預留位置取代為識別 ALB 存取日誌的 Amazon S3 儲存貯體位置的值。如需有關存取日誌檔案位置的詳細資訊，請參閱《Application Load Balancer 使用者指南**》中的[存取日誌檔案](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#access-log-file-format)。對於 `projection.day.range`，請用您要使用的開始日期取代 *2022*/*01*/*01*。成功執行查詢之後，您可以查詢資料表。您無須執行 `ALTER TABLE ADD PARTITION` 就能載入分割區。如需有關每個日誌檔案欄位的資訊，請參閱[存取日誌項目](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#access-log-entry-format)。

```
CREATE EXTERNAL TABLE IF NOT EXISTS alb_access_logs (
            type string,
            time string,
            elb string,
            client_ip string,
            client_port int,
            target_ip string,
            target_port int,
            request_processing_time double,
            target_processing_time double,
            response_processing_time double,
            elb_status_code int,
            target_status_code string,
            received_bytes bigint,
            sent_bytes bigint,
            request_verb string,
            request_url string,
            request_proto string,
            user_agent string,
            ssl_cipher string,
            ssl_protocol string,
            target_group_arn string,
            trace_id string,
            domain_name string,
            chosen_cert_arn string,
            matched_rule_priority string,
            request_creation_time string,
            actions_executed string,
            redirect_url string,
            lambda_error_reason string,
            target_port_list string,
            target_status_code_list string,
            classification string,
            classification_reason string,
            conn_trace_id string
            )
            PARTITIONED BY
            (
             day STRING
            )
            ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
            WITH SERDEPROPERTIES (
            'serialization.format' = '1',
            'input.regex' = 
        '([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*):([0-9]*) ([^ ]*)[:-]([0-9]*) ([-.0-9]*) ([-.0-9]*) ([-.0-9]*) (|[-0-9]*) (-|[-0-9]*) ([-0-9]*) ([-0-9]*) \"([^ ]*) (.*) (- |[^ ]*)\" \"([^\"]*)\" ([A-Z0-9-_]+) ([A-Za-z0-9.-]*) ([^ ]*) \"([^\"]*)\" \"([^\"]*)\" \"([^\"]*)\" ([-.0-9]*) ([^ ]*) \"([^\"]*)\" \"([^\"]*)\" \"([^ ]*)\" \"([^\\s]+?)\" \"([^\\s]+)\" \"([^ ]*)\" \"([^ ]*)\" ?([^ ]*)? ?( .*)?'
            )
            LOCATION 's3://amzn-s3-demo-bucket/AWSLogs/<ACCOUNT-NUMBER>/elasticloadbalancing/<REGION>/'
            TBLPROPERTIES
            (
             "projection.enabled" = "true",
             "projection.day.type" = "date",
             "projection.day.range" = "2022/01/01,NOW",
             "projection.day.format" = "yyyy/MM/dd",
             "projection.day.interval" = "1",
             "projection.day.interval.unit" = "DAYS",
             "storage.location.template" = "s3://amzn-s3-demo-bucket/AWSLogs/<ACCOUNT-NUMBER>/elasticloadbalancing/<REGION>/${day}"
            )
```

如需有關分割區投影的詳細資訊，請參閱[透過 Amazon Athena 使用分割區投影](partition-projection.md)。

**注意**  
我們建議在 `input.regex` 參數的結尾一律保留模式 *?( .\$1)?*，以便在新增新的 ALB 日誌欄位時，處理未來的日誌項目。

# ALB 存取日誌的查詢範例
<a name="query-alb-access-logs-examples"></a>

以下查詢會計算負載平衡器收到的 HTTP GET 請求，並依用戶端 IP 地址分組：

```
SELECT COUNT(request_verb) AS
 count,
 request_verb,
 client_ip
FROM alb_access_logs
GROUP BY request_verb, client_ip
LIMIT 100;
```

另一個查詢顯示 Safari 瀏覽器使用者造訪的 URL：

```
SELECT request_url
FROM alb_access_logs
WHERE user_agent LIKE '%Safari%'
LIMIT 10;
```

下列查詢顯示具有 ELB 狀態碼值大於或等於 500 的記錄。

```
SELECT * FROM alb_access_logs
WHERE elb_status_code >= 500
```

下列範例說明如何以 `datetime` 剖析日誌：

```
SELECT client_ip, sum(received_bytes) 
FROM alb_access_logs
WHERE parse_datetime(time,'yyyy-MM-dd''T''HH:mm:ss.SSSSSS''Z') 
     BETWEEN parse_datetime('2018-05-30-12:00:00','yyyy-MM-dd-HH:mm:ss') 
     AND parse_datetime('2018-05-31-00:00:00','yyyy-MM-dd-HH:mm:ss') 
GROUP BY client_ip;
```

下列查詢會查詢對指定日期的所有 ALB 存取日誌使用分割區投影的資料表。

```
SELECT * 
FROM alb_access_logs 
WHERE day = '2022/02/12'
```

# 建立 ALB 連線日誌的資料表
<a name="create-alb-connection-logs-table"></a>

1. 複製下列範例 `CREATE TABLE` 陳述式，並將其貼到 Athena 主控台查詢編輯器，然後針對自己的日誌項目要求視需要進行修改。如需有關 Athena 主控台入門的資訊，請參閱[開始使用](getting-started.md)。將 `LOCATION` 子句中的路徑取代為您的 Amazon S3 連線日誌資料夾位置。如需有關連線日誌檔案位置的詳細資訊，請參閱《Application Load Balancer 使用者指南**》中的[連線日誌檔案](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-connection-logs.html#connection-log-file-format)。如需有關每個日誌檔案欄位的資訊，請參閱[連線日誌項目](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-connection-logs.html#connection-log-entry-format)。

   ```
   CREATE EXTERNAL TABLE IF NOT EXISTS alb_connection_logs (
            time string,
            client_ip string,
            client_port int,
            listener_port int,
            tls_protocol string,
            tls_cipher string,
            tls_handshake_latency double,
            leaf_client_cert_subject string,
            leaf_client_cert_validity string,
            leaf_client_cert_serial_number string,
            tls_verify_status string,
            conn_trace_id string
            ) 
            ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
            WITH SERDEPROPERTIES (
            'serialization.format' = '1',
            'input.regex' =
             '([^ ]*) ([^ ]*) ([0-9]*) ([0-9]*) ([A-Za-z0-9.-]*) ([^ ]*) ([-.0-9]*) \"([^\"]*)\" ([^ ]*) ([^ ]*) ([^ ]*) ?([^ ]*)?( .*)?'
            )
            LOCATION 's3://amzn-s3-demo-bucket/connection-log-folder-path/'
   ```

1. 在 Athena 主控台中執行查詢。查詢完成之後，Athena 會註冊 `alb_connection_logs` 資料表，讓其中的資料可供您發出查詢。

# 使用分割區投影在 Athena 中建立 ALB 連線日誌的資料表
<a name="create-alb-connection-logs-table-partition-projection"></a>

由於 ALB 連線日誌具有您可以事先指定其分割區名稱的已知結構，您可以使用 Athena 分割區投影功能減少查詢執行時期並自動化分割區管理。分割區投影會在新增資料時自動新增分割區。因此您無需使用 `ALTER TABLE ADD PARTITION` 手動新增分割區。

以下範例 `CREATE TABLE` 陳述式會從指定日期到現在，對單一 AWS 區域的 ALB 連線日誌自動使用分割區投影。該陳述式基於上一節中的範例，但新增了 `PARTITIONED BY` 和 `TBLPROPERTIES` 子句以啟用分割區投影。在 `LOCATION` 和 `storage.location.template` 子句中，請將預留位置取代為識別 ALB 連線日誌的 Amazon S3 儲存貯體位置的值。如需有關連線日誌檔案位置的詳細資訊，請參閱《Application Load Balancer 使用者指南**》中的[連線日誌檔案](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-connection-logs.html#connection-log-file-format)。對於 `projection.day.range`，請用您要使用的開始日期取代 *2023*/*01*/*01*。成功執行查詢之後，您可以查詢資料表。您無須執行 `ALTER TABLE ADD PARTITION` 就能載入分割區。如需有關每個日誌檔案欄位的資訊，請參閱[連線日誌項目](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-connection-logs.html#connection-log-entry-format)。

```
CREATE EXTERNAL TABLE IF NOT EXISTS alb_connection_logs (
         time string,
         client_ip string,
         client_port int,
         listener_port int,
         tls_protocol string,
         tls_cipher string,
         tls_handshake_latency double,
         leaf_client_cert_subject string,
         leaf_client_cert_validity string,
         leaf_client_cert_serial_number string,
         tls_verify_status string,
         conn_trace_id string
         )
            PARTITIONED BY
            (
             day STRING
            )
            ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
            WITH SERDEPROPERTIES (
            'serialization.format' = '1',
            'input.regex' =
             '([^ ]*) ([^ ]*) ([0-9]*) ([0-9]*) ([A-Za-z0-9.-]*) ([^ ]*) ([-.0-9]*) \"([^\"]*)\" ([^ ]*) ([^ ]*) ([^ ]*) ?([^ ]*)?( .*)?'
            )
            LOCATION 's3://amzn-s3-demo-bucket/AWSLogs/<ACCOUNT-NUMBER>/elasticloadbalancing/<REGION>/'
            TBLPROPERTIES
            (
             "projection.enabled" = "true",
             "projection.day.type" = "date",
             "projection.day.range" = "2023/01/01,NOW",
             "projection.day.format" = "yyyy/MM/dd",
             "projection.day.interval" = "1",
             "projection.day.interval.unit" = "DAYS",
             "storage.location.template" = "s3://amzn-s3-demo-bucket/AWSLogs/<ACCOUNT-NUMBER>/elasticloadbalancing/<REGION>/${day}"
            )
```

如需有關分割區投影的詳細資訊，請參閱[透過 Amazon Athena 使用分割區投影](partition-projection.md)。

# ALB 連線日誌的查詢範例
<a name="query-alb-connection-logs-examples"></a>

下列查詢會計算 `tls_verify_status` 的值並非 `'Success'` 的出現次數，並依用戶端 IP 位址分組：

```
SELECT DISTINCT client_ip, count() AS count FROM alb_connection_logs
WHERE tls_verify_status != 'Success'
GROUP BY client_ip
ORDER BY count() DESC;
```

下列查詢會搜尋 `tls_handshake_latency` 的值在指定時間範圍內超過 2 秒的出現次數：

```
SELECT * FROM alb_connection_logs
WHERE 
  (
    parse_datetime(time, 'yyyy-MM-dd''T''HH:mm:ss.SSSSSS''Z') 
    BETWEEN 
    parse_datetime('2024-01-01-00:00:00', 'yyyy-MM-dd-HH:mm:ss') 
    AND 
    parse_datetime('2024-03-20-00:00:00', 'yyyy-MM-dd-HH:mm:ss') 
  ) 
  AND 
    (tls_handshake_latency >= 2.0);
```

# 其他資源
<a name="application-load-balancer-logs-additional-resources"></a>

如需有關使用 ALB 日誌的詳細資訊，請參閱以下資源。
+ *AWS 知識中心*中的[如何使用 Amazon Athena 分析 Application Load Balancer 存取日誌？](https://repost.aws/knowledge-center/athena-analyze-access-logs)。
+ 如需有關 Elastic Load Balancing 中的 HTTP 狀態碼的資訊，請參閱《*Application Load Balancers 使用者指南*》中的[對 Application Load Balancer 進行疑難排解](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-troubleshooting.html)。
+ *AWS 大數據部落格*中的[使用 AWS Glue 自訂分類器和 Amazon Athena 更有效地編目和分析 Application Load Balancer 日誌](https://aws.amazon.com/blogs/big-data/catalog-and-analyze-application-load-balancer-logs-more-efficiently-with-aws-glue-custom-classifiers-and-amazon-athena/)。