Creating Metrics from Logs with Metric Filters and Filter Patterns
Many important signals exist only in logs: an application error message, a failed login, a slow query. Metric filters turn matching log events into CloudWatch metrics that can be graphed and alarmed on. This lesson explains filter pattern syntax for text, space-delimited and JSON logs, how metric filters are configured, their limitations, and related features such as Contributor Insights and log anomaly detection.
Learning outcomes
After completing this lesson, you will be able to:
- Write filter patterns for unstructured text, space-delimited and JSON log events.
- Explain how metric filters assign metric values, default values and dimensions.
- Identify the limitations of metric filters, including that they apply only to new events.
- Describe Contributor Insights and log anomaly detection and when to use them instead of metric filters.
Filter Pattern Syntax
Filter patterns are used by metric filters, subscription filters and the FilterLogEvents search API. The syntax depends on the structure of the log events.
Unstructured text
Terms match events that contain them. ERROR matches events containing ERROR (matching is case-sensitive); ERROR Exception requires both terms; ?ERROR ?WARN matches either; ERROR -Timeout matches ERROR but excludes events containing Timeout; quoted phrases such as "connection refused" match exactly. Regular expressions can be used between percent signs, such as %5\d\d%.
Space-delimited
For logs with fields separated by spaces, such as web access logs, a pattern in square brackets names the fields and can test them: [ip, identity, user, timestamp, request, status_code=5*, size] matches events whose sixth field, the status code, starts with 5. Ellipses (...) match any number of fields.
JSON
For JSON events, selectors test fields: { $.level = "ERROR" }, { $.latencyMs > 1000 }, { ($.status = 500) || ($.status = 503) } and { $.user.id = "admin*" } with wildcards. Structured JSON logging makes reliable filters much easier to write than text matching.
| Pattern | Matches |
|---|---|
| ERROR | Events containing ERROR |
| ?ERROR ?CRITICAL | Events containing either term |
| ERROR -HealthCheck | ERROR events that do not contain HealthCheck |
| [ip, id, user, ts, req, status=4*, size] | Space-delimited events with a 4xx status field |
| { $.eventName = "ConsoleLogin" && $.responseElements.ConsoleLogin = "Failure" } | Failed console logins in CloudTrail logs |
| { $.latencyMs > 2000 } | JSON events with latency over two seconds |
Read the filter pattern
Configuring Metric Filters
A metric filter belongs to a log group and has a filter pattern, a metric namespace and name, a metric value and optionally a default value, dimensions and a unit. The metric value is usually 1, counting matching events, but it can be a field from the event, such as $.latencyMs, to publish a measured value. The default value, typically 0, is published for periods with log events but no matches, which keeps the metric continuous; without it, the metric has no data points when nothing matches, which affects alarm evaluation as described in the alarms lesson. For JSON and space-delimited logs, up to three fields can be used as dimensions, such as the API name, with care about cardinality.
aws logs put-metric-filter --log-group-name /orders/app \
--filter-name PaymentFailures \
--filter-pattern '{ $.event = "payment" && $.outcome = "failed" }' \
--metric-transformations \
metricName=PaymentFailures,metricNamespace=Orders/App,metricValue=1,defaultValue=0,dimensions={Provider=$.provider}Metric filters are a standard security monitoring tool. The CIS AWS Foundations Benchmark, for example, recommends metric filters and alarms on CloudTrail logs in CloudWatch Logs for unauthorised API calls, console sign-in without MFA, root account usage, IAM policy changes, CloudTrail configuration changes and security group changes.
Limitations
Metric filters have limitations that appear in scenarios. They evaluate only events ingested after the filter is created; they do not backfill history, for which Logs Insights is used. A log group can have a limited number of metric filters (100). They are not available on log groups in the Infrequent Access class. And they publish custom metrics, which are charged.
Metrics from logs
Contributor Insights and Log Anomaly Detection
Some questions are not about how many events occurred but about who or what caused them, such as which IP addresses generate the most rejected connections or which API keys cause the most errors. CloudWatch Contributor Insights rules analyse structured log events and report the top contributors to a metric, such as the top 10 source IPs, as time series, without publishing a metric per contributor. Built-in rules exist for DynamoDB and other services, and rules can be alarmed on, such as when any single contributor exceeds a threshold.
Log anomaly detection applies machine learning to a log group, learns its normal patterns and surfaces anomalies, such as a new error pattern or a sudden change in frequency of a pattern, without predefined filters. Pattern analysis in Logs Insights groups similar events into patterns, which helps understand large volumes of logs quickly. These complement metric filters, which only detect what someone anticipated.
Alerting on Application Errors
A Java application writes JSON logs. The team wants an alarm when more than 20 errors of any kind occur in five minutes, a graph of order processing latency, and a list of the customers who trigger the most errors.
-
Errors
Metric filter
{ $.level = "ERROR" }with metric value 1 and default value 0, and an alarm with a five-minute period and threshold 20. -
Latency
Metric filter
{ $.event = "order_processed" }with metric value$.durationMsand unit Milliseconds, graphed at p99. -
Top customers
A Contributor Insights rule keyed on
$.customerIdfor error events, instead of a dimension per customer.
A new metric filter for failed logins shows no data for incidents that occurred last week. Why?
Show answer
Metric filters process only log events ingested after the filter was created; they do not analyse past data. Use Logs Insights to analyse the historical events.
Exam Tips
Remember for the exam
- Filter patterns: terms (case-sensitive), ?OR, -exclude, space-delimited [field=value], JSON { $.field = value }.
- Metric filters publish a value of 1 or a field value; a default value of 0 keeps metrics continuous.
- Metric filters do not backfill historical events and are not available in the Infrequent Access log class.
- Contributor Insights finds top contributors without high-cardinality metrics; log anomaly detection finds unanticipated patterns.
- CIS benchmark alarms (root use, unauthorised calls, IAM and trail changes) are built from metric filters on CloudTrail logs in CloudWatch Logs.