Amazon Athena를 사용하여 Application Load Balancer 액세스 로그를 분석하려면 어떻게 해야 합니까?

6분 분량
0

Amazon Athena를 사용하여 Application Load Balancer 액세스 로그를 분석하려고 합니다.

Amazon Athena를 사용하여 Application Load Balancer 액세스 로그를 분석하려고 합니다.

간략한 설명

Elastic Load Balancing은 기본적으로 액세스 로깅을 활성화하지 않습니다. ](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/enable-access-logging.html) 액세스 로깅을 활성화[할 때 Amazon Simple Storage Service(Amazon S3) 버킷을 지정합니다. 모든 Application Load Balancer 및 Classic Load Balancer 액세스 로그는 Amazon S3 버킷에 저장됩니다. 로드 밸런서의 문제를 해결하거나 성능을 분석하려면 Athena를 사용하여 Amazon S3의 액세스 로그를 분석하십시오.

**참고:**Athena를 사용하여 Application Load Balancer 및 Classic Load Balancer의 액세스 로그를 분석할 수 있지만 이 해결 방법은 Application Load Balancer에만 적용됩니다.

해결 방법

Application Load Balancer 로그용 데이터베이스 및 테이블 생성

Athena에서 액세스 로그를 분석하려면 다음 단계에 따라 데이터베이스와 테이블을 생성하십시오.

1.    Athena 콘솔을 엽니다.

2.     데이터베이스를 생성하려면 쿼리 편집기에서 다음 명령을 실행합니다. S3 버킷과 동일한 AWS 리전에 데이터베이스를 생성하는 것이 가장 좋습니다.

create database alb_db

3.    2단계에서 생성한 데이터베이스에서 Application Load Balancer 로그에 대한 alb_logs 테이블을 생성합니다. 자세한 내용은 ](https://docs.aws.amazon.com/athena/latest/ug/application-load-balancer-logs.html#create-alb-table)Application Load Balancer 로그용 테이블 생성[을 참조하십시오.

참고: 쿼리 성능을 높이려면 파티션 프로젝션을 사용하여 테이블을 생성할 수 있습니다. 파티션 프로젝션에서 Athena는 AWS Glue 데이터 카탈로그와 같은 리포지토리에서 읽는 대신, 구성에서 파티션 값과 위치를 계산합니다. 자세한 내용은 ](https://docs.aws.amazon.com/athena/latest/ug/partition-projection.html)Amazon Athena를 사용한 파티션 프로젝션[을 참조하십시오.

CREATE EXTERNAL TABLE IF NOT EXISTS alb_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
            )
            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://your-alb-logs-directory/AWSLogs/1111222233334444/elasticloadbalancing//'
            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://your-alb-logs-directory/AWSLogs/1111222233334444/elasticloadbalancing//${day}"
            )

참고: 사용 사례에 따라 테이블 이름과 S3 위치를 바꿉니다.

또는 다음 쿼리를 사용하여 파티션이 있는 테이블을 생성합니다.

CREATE EXTERNAL TABLE IF NOT EXISTS alb_logs_partitioned (
            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 string,
            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
            )
            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://my_log_bucket/AWSLogs/1111222233334444/elasticloadbalancing/us-east-1/'

그런 다음, ALTER TABLE ADD PARTITION 명령을 사용하여 파티션을 로드합니다.

ALTER TABLE alb_logs_partitioned ADD
  PARTITION (day = '2022/05/21')
  LOCATION's3://my_log_bucket/AWSLogs/1111222233334444/elasticloadbalancing/us-east-1/2022/05/21/'

참고: Application Load Balancer 로그에서 AWS Glue 크롤러를 사용하는 것은 모범 사례가 아닙니다.

4.    탐색 창의 테이블 아래에 있는 메뉴에서 테이블 미리 보기를 선택합니다. 결과 창에서 Application Load Balancer 액세스 로그의 데이터를 볼 수 있습니다.

5.    쿼리 편집기를 사용하여 테이블에서 SQL 문을 실행합니다. 쿼리를 저장하거나 이전 쿼리를 보거나 쿼리 결과를 .csv 파일 형식으로 다운로드할 수 있습니다.

예제 쿼리

다음 예제에서는 쿼리에 맞게 테이블 이름, 열 값 및 기타 변수를 수정해야 합니다.

처음 100개의 액세스 로그 항목을 시간순으로 보기

분석 및 문제 해결에 다음 쿼리를 사용하십시오.

SELECT *  
FROM alb_logs  
ORDER by time ASC  
LIMIT 100

Application Load Balancer에 액세스한 모든 클라이언트 IP 주소와 Application Load Balancer에 액세스한 횟수 나열

분석 및 문제 해결에 다음 쿼리를 사용하십시오.

SELECT distinct client_ip, count() as count from alb_logs  
GROUP by client_ip  
ORDER by count() DESC;

요청 또는 응답 쌍으로 Application Load Balancer를 통과하는 평균 데이터 양(킬로바이트) 나열

분석 및 문제 해결에 다음 쿼리를 사용하십시오.

SELECT (avg(sent_bytes)/1000.0 + avg(received_bytes)/1000.0)  
as prewarm_kilobytes from alb_logs;

Application Load Balancer가 트래픽을 라우팅하는 모든 대상, 대상당 라우팅된 요청 수를 분포 비율별로 나열

다음 쿼리를 사용하여 잠재적인 대상 트래픽 불균형을 식별하십시오.

SELECT target_ip, (Count(target_ip)* 100.0 / (Select Count(*) From alb_logs))  
as backend_traffic_percentage  
FROM alb_logs  
GROUP by target_ip<  
ORDER By count() DESC;

클라이언트가 Application Load Balancer에 요청을 보낸 후 유휴 시간 초과가 경과하기 전에 연결을 닫은 횟수 나열(HTTP 460 오류)

다음 쿼리를 사용하여 HTTP 460 오류를 해결하십시오.

SELECT * from alb_logs where elb_status_code = '460';

리스너 규칙이 요청을 빈 대상 그룹에 전달했기 때문에 클라이언트 요청이 라우팅되지 않은 횟수 나열(HTTP 503 오류)

다음 쿼리를 사용하여 HTTP 503 오류를 해결하십시오.

SELECT * from alb_logs where elb_status_code = '503';

각 클라이언트가 지정된 URL을 방문한 횟수의 내림차순으로 클라이언트 나열

이 쿼리를 사용하여 트래픽 패턴을 분석하십시오.

SELECT client_ip, elb, request_url, count(*) as count from alb_logs  
GROUP by client_ip, elb, request_url  
ORDER by count DESC;

Firefox 사용자가 가장 자주 액세스한 10개 URL을 내림차순으로 나열

이 쿼리를 사용하여 트래픽 분포 및 패턴을 분석할 수 있습니다.

SELECT request_url, user_agent, count(*) as count  
FROM alb_logs  
WHERE user_agent LIKE '%Firefox%'  
GROUP by request_url, user_agent  
ORDER by count(*) DESC  
LIMIT 10;

각 클라이언트가 요청을 통해 Application Load Balancer에 보낸 데이터의 양(메가바이트)의 내림차순으로 클라이언트 나열

이 쿼리를 사용하여 트래픽 분포 및 패턴을 분석할 수 있습니다.

SELECT client_ip, sum(received_bytes/1000000.0) as client_datareceived_megabytes  
FROM alb_logs  
GROUP by client_ip  
ORDER by client_datareceived_megabytes DESC;

지정한 날짜 범위에서 대상 처리 시간이 5초 이상인 경우 나열

다음 쿼리를 사용하여 지정된 시간대의 지연 문제를 해결합니다.

SELECT * from alb_logs  
WHERE (parse_datetime(time,'yyyy-MM-dd''T''HH:mm:ss.SSSSSS''Z')  
    BETWEEN parse_datetime('2018-08-08-00:00:00','yyyy-MM-dd-HH:mm:ss')  
    AND parse_datetime('2018-08-08-02:00:00','yyyy-MM-dd-HH:mm:ss'))  
AND (target_processing_time >= 5.0);

클라이언트 IP 주소별로 그룹화한 로드 밸런서에서 수신한 HTTP GET 요청 수 계산

다음 쿼리를 사용하여 수신 트래픽 분포를 분석하십시오.

SELECT COUNT(request_verb)   
AS count, request_verb, client_ip   
FROM alb_logs_partitioned   
WHERE day = '2022/05/21'   
GROUP by request_verb, client_ip;
AWS 공식
AWS 공식업데이트됨 일 년 전
댓글 없음