SOA-C02Chapter 45 of 104Objective 1.1

CloudWatch Metric Filters from Log Groups

This chapter covers CloudWatch Metric Filters from Log Groups, a critical feature for extracting custom metrics from log data to monitor application behavior. For the SOA-C02 exam, this topic appears in roughly 5-8% of questions, often integrated with CloudWatch Logs, alarms, and dashboards. Understanding how metric filters work, their limitations, and common misconfigurations is essential for both the exam and real-world AWS operations.

25 min read
Intermediate
Updated May 31, 2026

CloudWatch Metric Filters as Airport Baggage Scanners

Imagine an airport baggage handling system. Thousands of bags (log events) flow through conveyor belts (log streams) into a central sorting facility (Log Group). At the entrance, each bag passes through an X-ray scanner (metric filter) that looks for specific patterns — like prohibited items (error codes) or count of bags per destination (metric values). The scanner doesn't stop the bag; it just counts and records what it sees. A security officer (CloudWatch alarm) watches the scanner's tally: if the number of flagged bags exceeds a threshold (e.g., 5 per minute), an alert triggers. The scanner has a limited field of view — it can only inspect bags that pass by; if a bag never goes through the scanner (log not matching filter pattern), it's invisible. Also, the scanner's counting mechanism works in real time but only reports every 60 seconds (metric resolution). If the conveyor belt is too fast (high log volume) and the scanner can't keep up, it might miss some bags (metric filter throttling). The scanner is configured with a specific pattern (filter pattern) — if you want to count bags with liquids, you set the pattern to look for 'liquid' in the bag's label. The scanner outputs a metric (e.g., 'LiquidBagsCount') that is then used for dashboards or alarms. In AWS, metric filters work exactly like this: they scan incoming log events in real time, extract or count based on a filter pattern, and emit custom metrics to CloudWatch, which can then trigger alarms or be graphed.

How It Actually Works

What Are CloudWatch Metric Filters?

CloudWatch Metric Filters are rules that you define on a CloudWatch Log Group to scan incoming log events for specific patterns and convert matching events into CloudWatch metric data points. They allow you to generate custom metrics from log data without writing custom code or processing logs externally. For example, you can count the number of ERROR log entries, track the average response time from an access log, or monitor the frequency of specific HTTP status codes.

Why They Exist

Before metric filters, you had to either send logs to a third-party monitoring tool or write custom scripts to parse logs and push metrics to CloudWatch. Metric filters provide a native, serverless, and cost-effective way to turn log data into actionable metrics. They are especially useful for operational health monitoring, SLA tracking, and security event detection.

How Metric Filters Work Internally

When you create a metric filter on a Log Group, CloudWatch Logs starts scanning every log event ingested into that group in real time. The filter pattern is a space-delimited list of keywords or a JSON expression that defines what to look for. For each incoming log event, the filter engine evaluates the pattern against the log message. If the pattern matches, the filter emits a metric data point to CloudWatch.

- Filter Pattern Types: - Space-delimited patterns: Used for unstructured logs like syslog or Apache access logs. Each term is a literal string or a numeric placeholder. For example, [ERROR] matches events containing the word ERROR. - JSON patterns: Used for structured JSON logs. You specify a JSON path and a condition. For example, $.status = 500 matches events where the status field is 500.

- Metric Value Assignment: - Count: The simplest metric is a count of matching events. The filter emits a value of 1 for each match, and CloudWatch aggregates these counts over the metric's period (default 1 minute). - Extracted value: You can extract a numeric value from the log event using a pattern with a numeric placeholder ($N). For example, in an Apache log with format %h %l %u %t "%r" %>s %b, you can extract the response size by defining a pattern like [..., $size, ...]. The extracted value is then emitted as the metric value.

- Metric Namespace and Name: - Each metric filter defines a custom metric namespace (e.g., MyApp/LogMetrics) and a metric name (e.g., ErrorCount). These become the metric's identity in CloudWatch.

- Metric Value and Default Value: - For count metrics, the value is always 1 per match. For extracted value metrics, the value is the extracted number. You can also specify a default value (e.g., 0) to emit when no match occurs, which is useful for detecting absence of events.

Key Parameters and Defaults

Filter Pattern: The pattern string. For space-delimited, use [ERROR] or [status, bytes]. For JSON, use { $.status = 500 }.

Metric Transformations: You can define multiple metric transformations in one filter. Each transformation has:

- Metric namespace (string, max 255 chars) - Metric name (string, max 255 chars) - Metric value (either $1 for extracted value or 1 for count) - Default value (optional, number) - Log Group: A filter is attached to one Log Group. It cannot span multiple Log Groups. - Real-time scanning: Filters are evaluated as log events are ingested. There is no batch delay; however, there is a latency of up to 60 seconds for the metric to appear in CloudWatch. - Throttling: CloudWatch Logs has a throttling limit for metric filters. By default, you can have up to 100 metric filters per account per region. Each filter can emit up to 10 metric values per log event. If the log ingestion rate exceeds the filter's processing capacity, some events may not be evaluated (though this is rare and typically at very high throughput).

Configuration and Verification

You can create a metric filter via AWS Management Console, AWS CLI, or SDK. Using AWS CLI:

aws logs put-metric-filter \
  --log-group-name "/aws/lambda/my-function" \
  --filter-name "ErrorCount" \
  --filter-pattern "ERROR" \
  --metric-transformations \
      metricName=ErrorCount,metricNamespace=MyApp,metricValue=1,defaultValue=0

To verify, list metric filters:

aws logs describe-metric-filters --log-group-name "/aws/lambda/my-function"

You can also test a filter pattern against sample log events using the test-metric-filter CLI command:

aws logs test-metric-filter \
  --filter-pattern "ERROR" \
  --log-event-messages "INFO: Success" "ERROR: Failed"

This returns which events matched and the emitted metric values.

Interaction with Related Technologies

CloudWatch Alarms: Metric filters are often used with CloudWatch Alarms. You create an alarm on the custom metric to trigger actions (e.g., SNS notification, Auto Scaling) when the metric breaches a threshold.

CloudWatch Dashboards: You can graph custom metrics from filters on dashboards for visualization.

CloudWatch Logs Insights: Metric filters are separate from Logs Insights. You can use both; filters provide real-time metrics, while Insights allows ad-hoc querying of log data.

AWS Lambda: Lambda functions often use metric filters to monitor error rates or invocation counts. For example, filter for "Task timed out" to alert on timeouts.

Amazon API Gateway: API Gateway access logs can be filtered to track 4xx/5xx rates.

Important Limitations

No historical backfill: Metric filters only scan log events ingested after the filter is created. They do not process existing log data.

Pattern complexity: Space-delimited patterns are limited to simple keyword matching. For complex parsing, use JSON patterns or consider using Logs Insights.

Metric resolution: Custom metrics from metric filters have a resolution of 1 minute (standard). High-resolution metrics (1 second) are not supported.

Cost: You are charged for each metric filter evaluated per log event, plus the standard CloudWatch metrics charges. At high log volumes, this can become expensive.

Common Exam Scenarios

The SOA-C02 exam often presents scenarios where you need to monitor specific log patterns. You might be asked to:

Create a metric filter to count 404 errors in ALB access logs.

Extract the request duration from an API Gateway log and set an alarm if the average exceeds 5 seconds.

Troubleshoot why a metric filter is not emitting data (e.g., wrong pattern, no new logs, filter not attached).

Choose between metric filter and Logs Insights subscription for real-time vs. historical analysis.

Walk-Through

1

Identify Log Group and Pattern

First, determine the Log Group that contains the log events you want to monitor. This could be from AWS services like Lambda, API Gateway, or custom applications. Then, analyze the log format to define the filter pattern. For unstructured logs, identify keywords or positions of numeric values. For structured JSON, identify the JSON path for the field of interest. For example, to monitor Lambda errors, the log group is `/aws/lambda/my-function` and the pattern is `ERROR`.

2

Create Metric Filter via CLI or Console

Using the AWS CLI, run `put-metric-filter` with the log group name, filter name, filter pattern, and metric transformations. In the console, navigate to the Log Group, select 'Metric Filters' tab, and click 'Create metric filter'. Define the pattern and test it with sample log events. Specify the metric namespace, name, value (1 for count or $1 for extracted), and optional default value. The filter is created immediately and starts scanning new logs.

3

Verify Filter Pattern with Test

Before finalizing, test the filter pattern using the `test-metric-filter` CLI command or the console's test feature. Provide sample log event messages that should and should not match. The test returns which events matched and the emitted metric values. This step catches pattern errors early. For example, if you expect `ERROR` to match but it doesn't, check for case sensitivity or whitespace.

4

Monitor Metric in CloudWatch

After the filter is created, wait up to 60 seconds for the first metric data points to appear. Navigate to CloudWatch Metrics and find the custom namespace (e.g., `MyApp/LogMetrics`). Select the metric (e.g., `ErrorCount`) and graph it. Verify that the metric shows values corresponding to the log events. If no data appears, check that new log events are being generated and that the pattern matches exactly.

5

Set Up Alarm and Notification

Once the metric is flowing, create a CloudWatch Alarm on it. In the alarm configuration, select the custom metric, define the condition (e.g., `ErrorCount > 10` for 5 consecutive periods), and set the evaluation period (e.g., 5 minutes). Configure the alarm action to send an SNS notification to a topic subscribed by email or Lambda. Test the alarm by generating matching log events to ensure notification fires.

What This Looks Like on the Job

Enterprise Scenario 1: Monitoring Error Rates in a Microservices Environment

A large e-commerce platform runs hundreds of microservices on AWS Lambda and ECS. Each service writes structured JSON logs to CloudWatch Logs. The operations team needs to detect spikes in 5xx errors across all services. They create metric filters on each Log Group with a JSON pattern { $.status >= 500 } and emit a count metric named 5xxCount. They use a single dashboard to graph all 5xxCount metrics. An alarm is set on each metric to trigger if the sum over 5 minutes exceeds a threshold. This setup allows real-time alerting without custom log processing. One common issue: if a developer changes the log format (e.g., renames status to httpStatus), the filter stops matching silently. To mitigate, the team uses Logs Insights to periodically validate that the pattern still matches.

Enterprise Scenario 2: Tracking Request Duration for SLA Compliance

A SaaS company uses Application Load Balancer (ALB) access logs to monitor response times. They need to ensure that 99% of requests complete in under 500ms. They create a metric filter on the ALB Log Group that extracts the request_processing_time field using a space-delimited pattern. The pattern is [..., $request_time, ...] where $request_time is the numeric value at a specific position. They emit the average of $request_time as a custom metric. An alarm alerts if the average exceeds 400ms for 10 minutes. However, they discover that the filter only captures a sample of logs because the ALB logs contain multiple entries per request. They switch to a JSON pattern to accurately parse the ALB log format. This scenario highlights the importance of understanding the exact log format before creating filters.

Performance and Scale Considerations

Metric filters are evaluated in real time but have a per-account throttling limit of 100 filters. For high-volume log streams (e.g., 10,000 log events per second), the filter engine may fall behind, causing some events to be skipped. AWS recommends using Kinesis Data Firehose or Lambda subscriptions for advanced processing. Also, each filter adds cost: $0.50 per filter per month plus $0.10 per million log events scanned. At scale, these costs can be significant. A common misconfiguration is creating too many fine-grained filters (e.g., one per error type) instead of using a single filter with multiple metric transformations.

How SOA-C02 Actually Tests This

What SOA-C02 Tests on This Topic

The exam objectives (Domain 1.1) include: 'Implement metric filters for log monitoring' and 'Troubleshoot metric filter issues'. Questions often present a scenario with a specific log format and ask you to choose the correct filter pattern or identify why a metric is not appearing. You must know the difference between space-delimited and JSON patterns, how to extract numeric values, and the default value feature.

Common Wrong Answers and Why Candidates Choose Them

1.

Using a filter pattern that is too broad or too narrow: Candidates often use ERROR when the log actually contains [ERROR] or error (case-sensitive). The exam tests that patterns are case-sensitive by default. They also mistakenly use regex-like syntax; metric filters do not support regular expressions.

2.

Expecting historical data to be scanned: A frequent trap is assuming that creating a metric filter will backfill metrics from existing logs. The exam will state that logs were generated before the filter was created, and ask why no metric data appears. The correct answer is that filters only apply to new log events.

3.

Confusing metric filters with subscription filters: Candidates often confuse metric filters with CloudWatch Logs subscription filters (which stream logs to Lambda, Kinesis, etc.). The exam may ask which service to use for real-time analysis vs. metric extraction.

4.

Misunderstanding extracted value syntax: For space-delimited patterns, the numeric placeholder is $N where N is the position (1-indexed). Candidates sometimes use $1 incorrectly or omit the square brackets around the pattern.

Specific Numbers and Terms to Memorize

Default metric value for count: 1

Maximum metric filters per account: 100

Metric resolution: 1 minute (standard)

Default value: Optional, can be 0 to emit when no match occurs

Filter pattern types: Space-delimited (literal), JSON (key-value conditions)

Metric namespace: Custom, up to 255 characters

Metric name: Custom, up to 255 characters

Edge Cases the Exam Loves to Test

Case sensitivity: The pattern error will not match Error or ERROR. Use [ERROR] for exact case match.

Multiple metric transformations: You can define up to 10 metric values per filter, each with different namespace/name.

Filter on multiple log streams: A filter on a Log Group applies to all log streams in that group.

No data after filter creation: If logs are generated but no metric appears, check the pattern or that the log group is correct.

How to Eliminate Wrong Answers

If the question involves extracting a number from a structured log (JSON), eliminate any space-delimited pattern option.

If the question mentions 'real-time' and 'metric', metric filter is correct; if it mentions 'historical analysis' or 'complex queries', Logs Insights is better.

If the scenario says 'logs were generated before filter creation', eliminate any answer that implies the filter will process those logs.

Key Takeaways

Metric filters scan log events in real time and emit CloudWatch custom metrics.

Filters only apply to new log events after creation; no backfill.

Filter patterns are case-sensitive and do not support regex.

Use space-delimited patterns for unstructured logs; JSON patterns for structured logs.

Extracted metric values must be numeric; use $1, $2, etc., for position-based extraction.

You can define up to 10 metric transformations per filter, each with different metric name/namespace.

Default value (e.g., 0) can be set to emit when no match occurs, useful for ‘absence’ detection.

Maximum 100 metric filters per account per region.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Metric Filter

Real-time continuous scanning of new log events

Emits custom metrics to CloudWatch automatically

Supports space-delimited and JSON patterns only

No historical data processing

Cost based on number of filters and log events scanned

Logs Insights Query

On-demand query of historical log data

Does not create persistent metrics; results are one-time

Supports full query language with regex, stats, and filters

Can query any log data within retention period

Cost based on amount of log data scanned per query

Watch Out for These

Mistake

Metric filters can parse existing log data once created.

Correct

Metric filters only process log events ingested after the filter is created. They do not backfill or scan historical log data. To analyze past logs, use CloudWatch Logs Insights.

Mistake

Metric filters support regular expressions in patterns.

Correct

Metric filters do not support regex. Space-delimited patterns are literal keyword matches; JSON patterns use exact equality or numeric comparisons. For regex, use a Lambda subscription filter.

Mistake

A metric filter on a Log Group applies to all log streams, including future ones.

Correct

This is true. The filter applies to all log streams within the Log Group, including newly created streams. However, it does not apply to other Log Groups.

Mistake

You can use metric filters to extract string values as metric data.

Correct

Metric values must be numeric. You can only extract numeric values from logs. String extraction is not supported. For string extraction, use Logs Insights or a subscription filter.

Mistake

Creating a metric filter automatically creates a CloudWatch alarm.

Correct

Metric filters only emit metric data. Alarms must be created separately on those metrics. The exam may ask you to differentiate between the two.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

Why is my metric filter not showing any data?

First, ensure that new log events are being generated after the filter was created. Check that the filter pattern exactly matches the log format (case-sensitive). Use the `test-metric-filter` CLI to verify. Also confirm the filter is attached to the correct Log Group. If using extracted values, ensure the numeric placeholder position is correct. Finally, check that you are looking at the correct metric namespace and name in CloudWatch.

Can I create a metric filter on a cross-account log group?

No, metric filters can only be created on Log Groups within the same AWS account. For cross-account log monitoring, use subscription filters with Kinesis Data Streams or Lambda.

What is the difference between a metric filter and a subscription filter?

A metric filter extracts metrics from logs and sends them to CloudWatch metrics. A subscription filter streams log events in real time to other AWS services like Lambda, Kinesis, or Elasticsearch for further processing. Subscription filters are more flexible but require additional services.

How do I extract a numeric value from a JSON log using a metric filter?

Use a JSON filter pattern like `{ $.response_time > 0 }` and set the metric value to `$.response_time`. Ensure the field exists and is numeric. You can also use numeric comparisons like `>`, `<`, `>=`, `<=`, `!=`, and `=`.

Can I use a metric filter to count occurrences of multiple patterns in one filter?

Yes, you can define multiple metric transformations in a single filter. Each transformation can have its own metric namespace, name, and value. For example, you could count both ERROR and WARN events with separate metrics from one filter.

What happens if my log volume exceeds the metric filter processing capacity?

CloudWatch Logs may throttle the filter, causing some log events to be skipped. This is rare but can occur at very high volumes (e.g., >10,000 events/second per filter). For high-throughput scenarios, consider using a subscription filter to Lambda for custom processing.

How do I set a default value for a metric filter?

When creating the metric transformation, specify a default value (e.g., 0). This value is emitted as a metric data point if no log events match the pattern during the 1-minute period. This is useful for detecting absence of expected logs.

Terms Worth Knowing

Ready to put this to the test?

You've just covered CloudWatch Metric Filters from Log Groups — now see how well it sticks with free SOA-C02 practice questions. Full explanations included, no account needed.

Done with this chapter?