Sub topic 10
Turning log events into metrics with metric filters
This chapter assumes you know what log groups and log streams are, can run AWS CLI commands, and understand namespaces, dimensions, and alarms from earlier chapters. Here you will learn how a metric filter converts log events into a metric, how to write filter patterns, and what commonly goes wrong.
Why metric filters exist
Logs record what happened. Alarms watch metrics. A metric filter connects the two. It scans log events as CloudWatch Logs ingests them, and each match produces a data point in a CloudWatch metric. You can then graph that metric, alarm on it, and add it to a dashboard like any other.
Typical uses:
- Count
ERRORlines in an application log. - Count HTTP 5xx responses in a web server access log.
- Sum bytes transferred, or track the largest latency value, from numbers written in the log.
- Count failed SSH logins from a system log.
How a metric filter works
A metric filter belongs to one log group. It has three parts:
- A filter pattern that decides which log events match.
- One or more metric transformations that say which metric receives a data point, and what value it carries.
- A log group to watch.
Three behaviors matter in practice:
- Filters are not retroactive. A filter only evaluates events ingested after you create it. It will not count events already stored in the log group. To analyze older data, use Logs Insights instead.
- The log data is unchanged. The filter reads events and does not alter or remove them.
- The metric is a custom metric. It lives in the namespace you name, and it is billed as a custom metric.
Creating a metric filter
This command, from the chapter plan, adds 1 to the ErrorCount metric in the MyApp namespace for every event in /app/web that contains the term ERROR:
aws logs put-metric-filter \
--log-group-name /app/web \
--filter-name ErrorCount \
--filter-pattern "ERROR" \
--metric-transformations metricName=ErrorCount,metricNamespace=MyApp,metricValue=1,defaultValue=0The --metric-transformations fields are:
| Field | Meaning |
|---|---|
| `metricName` | Name of the metric that receives data points. |
| `metricNamespace` | Namespace that holds the metric. |
| `metricValue` | The value published for each match. A constant such as `1` counts events. A field reference such as `$bytes` publishes a number from the log event. |
| `defaultValue` | Value published for periods in which the filter finds no match. Optional. |
| `dimensions` | Optional mapping of dimension names to fields extracted from the event. |
| `unit` | Optional unit, such as `Count` or `Milliseconds`. |
To confirm the filter exists, list the filters on the group:
aws logs describe-metric-filters --log-group-name /app/webTo remove it:
aws logs delete-metric-filter \
--log-group-name /app/web \
--filter-name ErrorCountDeleting a filter stops new data points. Data points already published stay in the metric until they expire.
Writing filter patterns
CloudWatch Logs supports several pattern styles. The right one depends on how your logs are formatted.
Plain terms
A bare term matches events that contain it. Matching is case-sensitive.
ERRORmatches events containingERROR, noterror."Connection refused"with quotes matches that exact phrase.ERROR timeoutmatches events containing both terms, in any order.?ERROR ?WARNmatches events containing either term. The?prefix means "or".ERROR -healthcheckmatches events containingERRORbut nothealthcheck.
JSON patterns
If each log event is a JSON object, you can test fields directly. The pattern is wrapped in braces and uses a $. path:
{ $.level = "ERROR" }
{ $.statusCode >= 500 }
{ ($.level = "ERROR") && ($.service = "checkout") }A numeric comparison such as $.statusCode >= 500 compares numbers. A string comparison such as $.level = "ERROR" compares text. Events that are not valid JSON do not match a JSON pattern.
Space-delimited patterns
For access logs with fields separated by spaces, name each field in square brackets. You can then filter and extract values by name:
[ip, user, username, timestamp, request, status_code = 5*, bytes]This matches events whose sixth field starts with 5. The wildcard * is allowed in string comparisons. The field names you choose become variables you can use in metricValue and dimensions.
Publishing a value from the log
A counter is the simplest case, but you can also publish a number found in the event. Suppose each event is JSON such as {"level":"INFO","route":"/pay","latencyMs":184}. This filter publishes the latency itself:
aws logs put-metric-filter \
--log-group-name /app/web \
--filter-name PayLatency \
--filter-pattern '{ $.route = "/pay" && $.latencyMs = * }' \
--metric-transformations metricName=PayLatency,metricNamespace=MyApp,metricValue='$.latencyMs',unit=MillisecondsEach matching event now contributes its own latencyMs as a data point. Because many events can arrive in the same period, you can ask for Average, Maximum, or percentiles when you query the metric. The pattern requires $.latencyMs = * so that events without the field do not match.
Dimensions from log fields
For JSON and space-delimited patterns, a transformation can attach dimensions taken from the event. For example, to count errors per service, use a JSON filter that extracts $.service:
aws logs put-metric-filter \
--log-group-name /app/web \
--filter-name ErrorsByService \
--filter-pattern '{ $.level = "ERROR" }' \
--metric-transformations '[{"metricName":"ErrorCount","metricNamespace":"MyApp","metricValue":"1","dimensions":{"Service":"$.service"}}]'Each distinct value of service creates a separate metric. A field with many possible values, such as a user ID or request ID, creates a very large number of metrics, and each one is billed. Use dimensions only for fields with a small, stable set of values.
Missing data and defaultValue
By default, a metric filter publishes a data point only when an event matches. In a quiet period the metric has no data at all, and an alarm on it sees missing data.
Setting defaultValue=0 makes the filter publish a zero for periods with no matches. This gives a continuous series, which is usually what you want for a count of errors.
Whether you set it changes how the alarm behaves:
- With
defaultValue=0, the alarm sees zeros and returns toOKnaturally when errors stop. - Without it, the alarm depends on its
--treat-missing-datasetting. ChoosenotBreachingfor error counts so silence is treated as healthy.
If you publish a value from the log (for example latency), do not set defaultValue. A zero would pull averages down and make latency look better than it is. Leave it unset, and set the alarm to treat missing data as notBreaching or ignore.
Alarming on the filtered metric
Once the metric exists, alarm on it like any other. This alarm enters ALARM when five or more errors occur in one minute:
aws cloudwatch put-metric-alarm \
--alarm-name web-error-burst \
--namespace MyApp \
--metric-name ErrorCount \
--statistic Sum \
--period 60 \
--evaluation-periods 1 \
--threshold 5 \
--comparison-operator GreaterThanOrEqualToThreshold \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:us-east-1:111122223333:ops-alertsUse Sum for a counter. Average of a metric whose every value is 1 is always 1, which tells you nothing about volume.
Common errors
| Symptom | Likely cause |
|---|---|
| Metric never appears | No new matching events since the filter was created, or the pattern is case-mismatched. |
| Counts lower than expected | Events written before the filter existed are not counted. |
| JSON filter matches nothing | Log lines carry a prefix (such as a timestamp) before the JSON, so the event is not valid JSON. |
| Alarm stays in `INSUFFICIENT_DATA` | No `defaultValue` and no matches, with the alarm not treating missing data as `notBreaching`. |
| Unexpected cost growth | A dimension taken from a high-cardinality field. |
You can test a pattern before creating the filter. The test-metric-filter command checks sample messages against a pattern:
aws logs test-metric-filter \
--filter-pattern '{ $.level = "ERROR" }' \
--log-event-messages '{"level":"ERROR","service":"checkout"}' '{"level":"INFO","service":"checkout"}'The output lists the events that matched. Run this first when a filter seems to count nothing.
Metric filters compared with Logs Insights
| Need | Use |
|---|---|
| Alarm on a log pattern continuously | Metric filter |
| Graph a trend over months cheaply | Metric filter |
| Investigate a past incident | Logs Insights |
| Group or sort by arbitrary fields ad hoc | Logs Insights |
| Analyze events from before you set anything up | Logs Insights |
A metric filter answers a question you decided in advance. Logs Insights answers questions you think of afterward.
Exercise
A log group receives JSON events such as {"level":"ERROR","service":"checkout"}. You create a metric filter with pattern { $.level = "ERROR" } and metricValue=1, with no defaultValue, then build an alarm with Statistic Average, threshold 1, and default missing-data handling. Errors occurred yesterday, but the alarm never fires today, and the metric shows no data during the day. Name two things to change so the setup behaves as intended.
Show answer
First, change the alarm statistic to Sum, because Average of a metric whose values are all 1 is always 1 and does not reflect volume. Pick a threshold that represents a real error count, such as 5 per minute. Second, handle quiet periods deliberately: set defaultValue=0 on the filter so the metric has a continuous series, or set the alarm's --treat-missing-data to notBreaching so gaps count as healthy. Also remember that events from yesterday are not counted by a filter created after they were ingested.
Exercise
Why should you avoid a metric filter dimension taken from $.userId, and what would you use instead to investigate one user's errors?
Show answer
Each distinct userId would create a separate custom metric, and each metric is billed, so cost and metric count grow with your user base. Use Logs Insights to filter on a specific userId when investigating, for example with filter userId = "u-123" in a query, and keep metric dimensions to low-cardinality fields such as service or environment.