Part 2: CloudWatch Query Syntax Fundamentals

Learning Query Commands

After mastering basic queries, I needed to understand the full power of CloudWatch Logs Insights syntax. This part covers all the essential commands I use daily.

Query Command Structure

Every CloudWatch Logs Insights query follows this pattern:

<command> <parameters>
| <command> <parameters>
| <command> <parameters>

Commands are chained with the pipe operator (|).

Core Commands

1. fields - Selecting Data

The fields command specifies which fields to display or extract.

# Select specific fields
fields @timestamp, @message

# Select all fields
fields @timestamp, @message, @logStream, @log

# Select and rename
fields @timestamp as time, @message as log_message

# Select using wildcards (for JSON logs)
fields @timestamp, request.*

Real Example from Lambda Logs

2. filter - Filtering Data

The filter command reduces results based on conditions.

Filter Operators

Operator
Description
Example

=

Equals

statusCode = 200

!=

Not equals

statusCode != 200

<

Less than

duration < 100

<=

Less than or equal

duration <= 100

>

Greater than

duration > 1000

>=

Greater than or equal

duration >= 1000

like

Pattern match

@message like /ERROR/

not like

Pattern not match

@message not like /DEBUG/

in

Value in list

statusCode in [400, 404, 500]

not in

Value not in list

statusCode not in [200, 201]

Real Example from API Gateway Logs

3. stats - Aggregating Data

The stats command performs aggregations.

Aggregation Functions

Function
Description
Example

count()

Count events

stats count()

count_distinct()

Count unique values

stats count_distinct(userId)

sum()

Sum values

stats sum(bytes)

avg()

Average

stats avg(duration)

min()

Minimum

stats min(duration)

max()

Maximum

stats max(duration)

stddev()

Standard deviation

stats stddev(latency)

pct()

Percentile

stats pct(duration, 95)

Real Example from Application Logs

4. sort - Ordering Results

The sort command orders results.

Real Example

5. limit - Restricting Results

The limit command restricts the number of results.

6. parse - Extracting Fields

The parse command extracts fields using patterns.

Parse Patterns

Glob patterns (simpler):

Regular expressions (more powerful):

Real Example from Application Logs

7. display - Showing Fields

The display command shows visualization fields (similar to fields but for viz).

Usually used with visualizations.

Working with Time

Time operations are crucial in log analysis.

Time Functions

Time-Based Queries

Events in Last Hour

Events Per 5-Minute Interval

Events Per Hour

Real Example: Request Rate Over Time

Data Types

Understanding data types helps write correct queries.

Supported Types

  • String: Text values ("hello", log messages)

  • Number: Integers and floats (200, 12.34)

  • Boolean: true or false

  • Timestamp: ISO 8601 format

Type Conversion

CloudWatch automatically converts types, but you can be explicit:

String Operations

String Functions

String Matching

Real Example: Extract User Agent Info

Number Operations

Arithmetic

Math Functions

Real Example: Convert Bytes to GB

Working with JSON Logs

Many AWS services log in JSON format. Here's how I query them:

Accessing JSON Fields

If logs are JSON, CloudWatch automatically parses them:

Query:

Nested JSON Fields

Query:

Real Example: Lambda Logs (JSON)

Boolean Logic

AND Logic

OR Logic

Combined Logic

Conditional Expressions

if Function

Real Example: Categorize Response Times

Checking for Field Existence

ispresent Function

Real Example: Handle Optional Fields

Practical Query Patterns

Pattern 1: Error Rate Over Time

Pattern 2: Top Error Messages

Pattern 3: Performance by Endpoint

Pattern 4: User Activity Analysis

Pattern 5: Time-Based Comparison

Query Optimization Tips

From my experience:

1. Filter Early

2. Limit Field Selection

3. Use Aggregations Wisely

4. Specific Time Ranges

Common Syntax Errors I Made

Error 1: Missing Pipes

Error 2: Incorrect String Matching

Error 3: Type Mismatches

Error 4: Invalid Field Names

Key Takeaways

  • Six core commands: fields, filter, stats, sort, limit, parse

  • Filter early in query for better performance

  • Use stats for aggregations and analytics

  • parse extracts custom fields from unstructured logs

  • JSON logs are automatically parsed

  • Time functions like ago() and bin() are essential

  • String and number operations provide flexibility

  • Use ispresent() to handle optional fields

In Part 3, we'll explore advanced query operations including complex parsing, regular expressions, and time-series analysis for production monitoring.

Last updated