

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 샘플 쿼리
<a name="CWL_QuerySyntax-examples"></a>

이 섹션에는 [CloudWatch 콘솔](https://console.aws.amazon.com/cloudwatch/)에서 실행할 수 있는 일반적이고 유용한 쿼리 명령 목록이 포함되어 있습니다. 쿼리 명령을 실행하는 방법에 대한 자세한 내용은 *Amazon CloudWatch Logs User Guide*의 [Tutorial: Run and modify a sample query](https://docs.aws.amazon.com/en_us/AmazonCloudWatch/latest/logs/CWL_AnalyzeLogData_RunSampleQuery.html)을 참조하세요.

쿼리 구문에 대한 자세한 내용은 [CloudWatch Logs Insights 언어 쿼리 구문](CWL_QuerySyntax.md)을 참조하세요.

**Topics**
+ [

## 일반 쿼리
](#CWL_QuerySyntax-examples-general)
+ [

## Lambda 로그에 대한 쿼리
](#CWL_QuerySyntax-examples-Lambda)
+ [

## Amazon VPC 흐름 로그에 대한 쿼리
](#CWL_QuerySyntax-examples-VPC)
+ [

## Route 53 로그에 대한 쿼리
](#CWL_QuerySyntax-examples-Route53)
+ [

## CloudTrail 로그에 대한 쿼리
](#CWL_QuerySyntax-examples-CloudTrail)
+ [

## 에 대한 쿼리 Amazon API Gateway
](#CWL_QuerySyntax-examples-APIGateway)
+ [

## NAT 게이트웨이에 대한 쿼리
](#CWL_QuerySyntax-examples-NATGateway)
+ [

## Apache 서버 로그에 대한 쿼리
](#CWL_QuerySyntax-examples-Apache)
+ [

## Amazon EventBridge에 대한 쿼리
](#CWL_QuerySyntax-examples-EventBridge)
+ [

## 구문 분석 명령의 예제
](#CWL_QuerySyntax-examples-parse)

## 일반 쿼리
<a name="CWL_QuerySyntax-examples-general"></a>

**최근에 추가된 로그 이벤트 25개를 찾습니다.**

```
fields @timestamp, @message | sort @timestamp desc | limit 25
```

**시간당 발생한 예외 횟수 목록을 가져옵니다.**

```
filter @message like /Exception/ 
    | stats count(*) as exceptionCount by bin(1h)
    | sort exceptionCount desc
```

**예외에 해당되지 않는 로그 이벤트 목록을 가져옵니다.**

```
fields @message | filter @message not like /Exception/
```

**`server` 필드의 각 고유 값에 대한 최신 로그 이벤트를 가져옵니다.**

```
fields @timestamp, server, severity, message 
| sort @timestamp asc 
| dedup server
```

**각 `severity` 유형에 대한 `server` 필드의 각 고유 값에 대한 최신 로그 이벤트를 가져옵니다.**

```
fields @timestamp, server, severity, message 
| sort @timestamp desc 
| dedup server, severity
```

## Lambda 로그에 대한 쿼리
<a name="CWL_QuerySyntax-examples-Lambda"></a>

**과다 프로비저닝된 메모리의 양을 확인합니다.**

```
filter @type = "REPORT"
    | stats max(@memorySize / 1000 / 1000) as provisonedMemoryMB,
        min(@maxMemoryUsed / 1000 / 1000) as smallestMemoryRequestMB,
        avg(@maxMemoryUsed / 1000 / 1000) as avgMemoryUsedMB,
        max(@maxMemoryUsed / 1000 / 1000) as maxMemoryUsedMB,
        provisonedMemoryMB - maxMemoryUsedMB as overProvisionedMB
```

**지연 보고서를 생성합니다.**

```
filter @type = "REPORT" |
    stats avg(@duration), max(@duration), min(@duration) by bin(5m)
```

**느린 함수 간접 호출을 검색하고 재시도 또는 클라이언트측 코드에서 발생할 수 있는 중복 요청을 제거합니다. 이 쿼리에서 `@duration`은 밀리초 단위입니다.**

```
fields @timestamp, @requestId, @message, @logStream 
| filter @type = "REPORT" and @duration > 1000
| sort @timestamp desc
| dedup @requestId 
| limit 20
```

## Amazon VPC 흐름 로그에 대한 쿼리
<a name="CWL_QuerySyntax-examples-VPC"></a>

**호스트 간에 상위 15개의 패킷 전송을 찾습니다.**

```
stats sum(packets) as packetsTransferred by srcAddr, dstAddr
    | sort packetsTransferred  desc
    | limit 15
```

**지정된 서브넷의 호스트에 대해 상위 15개 바이트 전송을 찾습니다.**

```
filter isIpv4InSubnet(srcAddr, "192.0.2.0/24")
    | stats sum(bytes) as bytesTransferred by dstAddr
    | sort bytesTransferred desc
    | limit 15
```

**데이터 전송 프로토콜로 UDP를 사용하는 IP 주소를 찾습니다.**

```
filter protocol=17 | stats count(*) by srcAddr
```

**캡처 기간 중 흐름 레코드를 건너뛴 IP 주소를 찾습니다.**

```
filter logStatus="SKIPDATA"
    | stats count(*) by bin(1h) as t
    | sort t
```

**네트워크 연결 문제 해결에 도움이 되도록 각 연결에 대한 단일 레코드를 찾습니다.**

```
fields @timestamp, srcAddr, dstAddr, srcPort, dstPort, protocol, bytes 
| filter logStream = 'vpc-flow-logs' and interfaceId = 'eni-0123456789abcdef0' 
| sort @timestamp desc 
| dedup srcAddr, dstAddr, srcPort, dstPort, protocol 
| limit 20
```

## Route 53 로그에 대한 쿼리
<a name="CWL_QuerySyntax-examples-Route53"></a>

**시간당 레코드 배포를 쿼리 유형별로 찾습니다.**

```
stats count(*) by queryType, bin(1h)
```

**요청 횟수가 가장 많은 DNS 해석기 10개를 찾습니다.**

```
stats count(*) as numRequests by resolverIp
    | sort numRequests desc
    | limit 10
```

**서버가 DNS 요청을 완료하지 못한 도메인 및 하위 도메인별 레코드의 수를 찾습니다.**

```
filter responseCode="SERVFAIL" | stats count(*) by queryName
```

## CloudTrail 로그에 대한 쿼리
<a name="CWL_QuerySyntax-examples-CloudTrail"></a>

**각 서비스, 이벤트 유형 및 AWS 리전에 대한 로그 항목 수를 찾습니다.**

```
stats count(*) by eventSource, eventName, awsRegion
```

**지정된 AWS 리전에서 시작되거나 중지된 Amazon EC2 호스트를 찾습니다.**

```
filter (eventName="StartInstances" or eventName="StopInstances") and awsRegion="us-east-2"
```

**새로 생성된 IAM 사용자의 AWS 리전, 사용자 이름 및 ARNs 찾습니다.**

```
filter eventName="CreateUser"
    | fields awsRegion, requestParameters.userName, responseElements.user.arn
```

**API `UpdateTrail`을 간접 호출하는 중 예외가 발생한 레코드의 수를 찾습니다.**

```
filter eventName="UpdateTrail" and ispresent(errorCode)
    | stats count(*) by errorCode, errorMessage
```

**TLS 1.0 또는 1.1이 사용된 로그 항목을 찾습니다.**

```
filter tlsDetails.tlsVersion in [ "TLSv1", "TLSv1.1" ]
| stats count(*) as numOutdatedTlsCalls by userIdentity.accountId, recipientAccountId, eventSource, eventName, awsRegion, tlsDetails.tlsVersion, tlsDetails.cipherSuite, userAgent
| sort eventSource, eventName, awsRegion, tlsDetails.tlsVersion
```

**TLS 버전 1.0 또는 1.1을 사용한 서비스당 직접 호출의 수를 찾습니다.**

```
filter tlsDetails.tlsVersion in [ "TLSv1", "TLSv1.1" ]
| stats count(*) as numOutdatedTlsCalls by eventSource
| sort numOutdatedTlsCalls desc
```

## 에 대한 쿼리 Amazon API Gateway
<a name="CWL_QuerySyntax-examples-APIGateway"></a>

마지막 10개의 4XX 오류 찾기

```
fields @timestamp, status, ip, path, httpMethod
| filter status>=400 and status<=499
| sort @timestamp desc
| limit 10
```

 Amazon API Gateway 액세스 로그 그룹에서 가장 오래 실행되는 Amazon API Gateway 요청 10개 식별

```
fields @timestamp, status, ip, path, httpMethod, responseLatency
| sort responseLatency desc
| limit 10
```

 Amazon API Gateway  액세스 로그 그룹에서 가장 많이 사용되는 API 경로 목록 반환

```
stats count(*) as requestCount by path
| sort requestCount desc
| limit 10
```

 Amazon API Gateway  액세스 로그 그룹에 대한 통합 지연 시간 보고서 생성

```
filter status=200
| stats avg(integrationLatency), max(integrationLatency), 
min(integrationLatency) by bin(1m)
```

## NAT 게이트웨이에 대한 쿼리
<a name="CWL_QuerySyntax-examples-NATGateway"></a>

 AWS 청구서에서 일반 비용보다 높은 비용이 발생하는 경우 CloudWatch Logs Insights를 사용하여 상위 기여자를 찾을 수 있습니다. 다음 쿼리 명령에 대한 자세한 내용은 AWS 프리미엄 지원 페이지의 [VPC에서 NAT 게이트웨이를 통한 트래픽에 대한 상위 기여자를 찾으려면 어떻게 해야 합니까?](https://aws.amazon.com/premiumsupport/knowledge-center/vpc-find-traffic-sources-nat-gateway/)를 참조하세요.

**참고**  
다음 쿼리 명령에서 'x.x.x.x'를 NAT 게이트웨이의 프라이빗 IP로 바꾸고 'y.y'를 VPC CIDR 범위의 처음 두 옥텟으로 바꿉니다.

**NAT 게이트웨이를 통해 가장 많은 트래픽을 전송하는 인스턴스를 찾습니다.**

```
filter (dstAddr like 'x.x.x.x' and srcAddr like 'y.y.') 
| stats sum(bytes) as bytesTransferred by srcAddr, dstAddr
| sort bytesTransferred desc
| limit 10
```

**NAT 게이트웨이의 인스턴스에서 송수신되는 트래픽을 확인합니다.**

```
filter (dstAddr like 'x.x.x.x' and srcAddr like 'y.y.') or (srcAddr like 'xxx.xx.xx.xx' and dstAddr like 'y.y.')
| stats sum(bytes) as bytesTransferred by srcAddr, dstAddr
| sort bytesTransferred desc
| limit 10
```

**VPC 인스턴스가 업로드 및 다운로드를 위해 가장 자주 통신하는 인터넷 대상을 결정합니다.**

*****업로드용*****

```
filter (srcAddr like 'x.x.x.x' and dstAddr not like 'y.y.') 
| stats sum(bytes) as bytesTransferred by srcAddr, dstAddr
| sort bytesTransferred desc
| limit 10
```

*****다운로드용*****

```
filter (dstAddr like 'x.x.x.x' and srcAddr not like 'y.y.') 
| stats sum(bytes) as bytesTransferred by srcAddr, dstAddr
| sort bytesTransferred desc
| limit 10
```

## Apache 서버 로그에 대한 쿼리
<a name="CWL_QuerySyntax-examples-Apache"></a>

CloudWatch Logs Insights를 사용하여 Apache 서버 로그를 쿼리할 수 있습니다. 다음 쿼리에 대한 자세한 내용은 [ Cloud Operations & Migrations 블로그의 Simplifying Apache server logs with CloudWatch Logs Insights](https://aws.amazon.com/blogs/mt/simplifying-apache-server-logs-with-amazon-cloudwatch-logs-insights/)를 참조하세요. AWS 

**가장 관련성이 높은 필드를 찾아서 액세스 로그를 검토하고 애플리케이션의 */admin* 경로에서 트래픽을 확인할 수 있습니다.**

```
fields @timestamp, remoteIP, request, status, filename| sort @timestamp desc
| filter filename="/var/www/html/admin"
| limit 20
```

**상태 코드 '200'(성공)을 사용하여 기본 페이지에 액세스한 고유 GET 요청 수를 찾습니다.**

```
fields @timestamp, remoteIP, method, status
| filter status="200" and referrer= http://34.250.27.141/ and method= "GET"
| stats count_distinct(remoteIP) as UniqueVisits
| limit 10
```

**Apache 서비스가 다시 시작된 횟수를 찾습니다.**

```
fields @timestamp, function, process, message
| filter message like "resuming normal operations"
| sort @timestamp desc
| limit 20
```

## Amazon EventBridge에 대한 쿼리
<a name="CWL_QuerySyntax-examples-EventBridge"></a>

이벤트 세부 정보 유형별로 그룹화된 EventBridge 이벤트의 수 가져오기

```
fields @timestamp, @message
| stats count(*) as numberOfEvents by `detail-type`
| sort numberOfEvents desc
```

## 구문 분석 명령의 예제
<a name="CWL_QuerySyntax-examples-parse"></a>

**glob 표현식을 사용하여 로그 필드 `@message`에서 필드 `@user`, `@method` 및 `@latency`를 추출하고 `@method` 및 `@user`의 고유한 개별 조합에 대한 평균 지연 시간을 반환합니다.**

```
parse @message "user=*, method:*, latency := *" as @user,
    @method, @latency | stats avg(@latency) by @method,
    @user
```

**정규식을 사용하여 로그 필드 `@message`에서 필드 `@user2`, `@method2` 및 `@latency2`를 추출하고 `@method2` 및 `@user2`의 고유한 개별 조합에 대한 평균 지연 시간을 반환합니다.**

```
parse @message /user=(?<user2>.*?), method:(?<method2>.*?),
    latency := (?<latency2>.*?)/ | stats avg(latency2) by @method2, 
    @user2
```

**`loggingTime`, `loggingType` 및 `loggingMessage` 필드를 추출하고 `ERROR` 또는 `INFO` 문자열이 포함된 이벤트를 기록하도록 필터링한 다음 `ERROR` 문자열이 포함된 이벤트에 대해 `loggingMessage` 및 `loggingType` 필드만 표시합니다.**

```
FIELDS @message
    | PARSE @message "* [*] *" as loggingTime, loggingType, loggingMessage
    | FILTER loggingType IN ["ERROR", "INFO"]
    | DISPLAY loggingMessage, loggingType = "ERROR" as isError
```