Home AWSCloudWatch Logs Insights: Query EC2 Logs Like a Pro

CloudWatch Logs Insights: Query EC2 Logs Like a Pro

by Knowledge Base Linux
CloudWatch Logs Insights dashboard searching EC2 log streams with filters and charts

Your EC2 fleet writes thousands of log lines a minute, and the one line that explains an outage is somewhere in the middle of them. Scrolling through CloudWatch log streams by hand is slow and unreliable. CloudWatch Logs Insights changes the job from reading logs to querying them: a purpose-built query language that searches, filters, aggregates, and visualizes log data across whole log groups in seconds.

CloudWatch Logs Insights grouping log events by time and filtering error patterns

This guide shows how to send EC2 logs to CloudWatch, write your first Logs Insights queries, and build the queries that actually solve incidents: finding errors, counting them over time, and tracing a single request. For alerting on top of these logs, see our CloudWatch alarms guide, and for shell access without open ports, our AWS Session Manager guide.

Prerequisites

  • An AWS account with an EC2 instance running Amazon Linux 2023 or Ubuntu.
  • The CloudWatch agent installed on the instance (or logs already flowing into a CloudWatch log group).
  • IAM permissions to read CloudWatch Logs (logs:StartQuery, logs:GetQueryResults, and logs:FilterLogEvents are the essentials).

Getting EC2 Logs into CloudWatch

Logs Insights can only query log groups that exist, so the first step is shipping logs. On Amazon Linux 2023, install the CloudWatch agent, then create a minimal configuration that collects system logs and your application log:

sudo yum install -y amazon-cloudwatch-agent
sudo tee /opt/aws/amazon-cloudwatch-agent/etc/config.json > /dev/null <<'EOF'
{
  "logs": {
    "logs_collected": {
      "files": {
        "collect_list": [
          {
            "file_path": "/var/log/messages",
            "log_group_name": "ec2-system-logs",
            "log_stream_name": "{instance_id}"
          },
          {
            "file_path": "/var/log/myapp/app.log",
            "log_group_name": "myapp-logs",
            "log_stream_name": "{instance_id}"
          }
        ]
      }
    }
  }
}
EOF
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
  -a fetch-config -m ec2 -s \
  -c file:/opt/aws/amazon-cloudwatch-agent/etc/config.json

On Ubuntu, install the same agent with apt and use the same configuration file and control command. Verify logs are arriving in the CloudWatch console under Logs > Log groups before moving on — a query against an empty log group returns nothing, which looks exactly like a query that found nothing.

Your First CloudWatch Logs Insights Queries

Open CloudWatch > Logs Insights, select one or more log groups, and set a time range. The simplest useful query filters for error-level lines:

fields @timestamp, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 100

Every Logs Insights query is a pipeline: fields picks columns, filter narrows rows, sort orders them, and limit caps the output. A few building blocks cover most incident work. Count errors per minute to see when a problem started:

fields @timestamp
| filter @message like /ERROR/
| stats count() by bin(1m)

Find the most common error messages, so you fix the frequent cause first instead of the first one you noticed:

fields @message
| filter @message like /ERROR/
| stats count() as errorCount by @message
| sort errorCount desc
| limit 20

Group by log stream (which is usually the instance ID) to see whether an error affects the whole fleet or one bad host:

fields @logStream, @message
| filter @message like /ERROR/
| stats count() by @logStream
| sort count desc

CloudWatch Logs Insights for Real Incidents

Incident queries usually start from a symptom. For HTTP 5xx errors in an application log, extract the status code from the message and aggregate:

fields @timestamp, @message
| parse @message /(?<status>\d{3})/
| filter status >= 500
| stats count() by status, bin(5m)

For tracing a single request across services, filter by a request or correlation ID if your application logs one — and if it does not, adding one is the highest-value logging improvement most teams can make:

fields @timestamp, @message
| filter @message like /req-9f3a1c/
| sort @timestamp asc

For slow requests, parse a duration field and look at the tail, not the average. Averages hide the slow requests your users actually notice:

fields @timestamp, @message
| parse @message /duration=(?<duration_ms>\d+)/
| filter duration_ms > 1000
| stats count(), avg(duration_ms), max(duration_ms) by bin(5m)

Save queries you reuse — the console lets you save them by name — and build a small library: errors by service, 5xx rate, slow requests, and log volume by host. During an incident, running a saved query beats writing a new one under pressure.

Costs, Limits, and Good Habits

Logs Insights charges per gigabyte scanned, so broad queries over long time ranges over large log groups cost real money. Narrow the time range first, select only the log groups you need, and put the most selective filter early in the pipeline. The limit command caps returned rows but does not reduce scanned data — filtering does that.

Two more habits pay off. First, keep log volume under control at the source: debug-level logs in production are expensive twice over, once in ingestion and once in every query that scans them. Second, set retention on log groups (for example 30 days for application logs) so old data stops accumulating cost automatically. Both settings live in the log group configuration and take effect without any code change.

Troubleshooting CloudWatch Logs Insights

Query returns no results. Check three things in order: the time range (Logs Insights defaults to a short window), the log group selection, and the filter text. A case-sensitive like match on error will miss ERROR; use a case-insensitive pattern or match the exact case your application writes.

“No log groups found” or permission errors. The IAM role needs logs:DescribeLogGroups in addition to query permissions, and the console region must match the region where the logs live. Logs Insights does not search across regions.

Queries time out on large log groups. Narrow the time range, add a selective filter, or split the query by log stream. Queries are limited in scanned data and duration; a query that scans everything is usually a query that has not been narrowed enough.

Parsed fields are empty. The parse pattern must match the log format exactly, including spacing. Test the pattern on a single known log line first, then generalize. Named capture groups that do not match produce empty fields, not errors, which makes a bad pattern easy to miss.

Conclusion

CloudWatch Logs Insights turns EC2 log investigation from scrolling into querying: filter for the error, aggregate by time and host, parse the fields that matter, and save the queries you will need again. Start by shipping your system and application logs with the CloudWatch agent, then build the four core queries — errors over time, top errors, errors by host, and slow requests. The full query syntax is documented in the CloudWatch Logs Insights query syntax reference. The next time an instance misbehaves, the answer will be one query away instead of one long scroll away.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.