Counting CloudWatch Logs Events with a Metric Filter in AWS Emulator
A CloudWatch Logs metric filter counts how many times ERROR appears in your logs, or how many HTTP 5xx responses occurred, as a CloudWatch metric. This article shows how to check an alarm setup that fires on an error count before you deploy it to production, locally or in CI. It runs AWS Emulator on your machine, creates a filter, writes logs, and follows the count into the metric. The commands and output are copied from the test environment.
The test environment was Ubuntu 24.04 (x86_64), AWS Emulator 1.0.757 (released November 28, 2026), and AWS CLI 2.42.5. No AWS account or credentials were used. I did not verify how real CloudWatch Logs and CloudWatch behave: when metrics appear, the SampleCount values, how statistics are timestamped, how test-metric-filter counts eventNumber, or pricing. Where this article mentions those, it relies on the official documentation. I only tested operations through the AWS CLI. I did not test creating filters through the management console, SDKs, or CloudFormation, and I did not test alarms that use the filter counts.
- 1. Start the emulator and point the AWS CLI at it
- 2. Prepare a script to write logs
- 3. Check the pattern with test-metric-filter first
- 4. Create a filter with put-metric-filter
- 5. Write logs and read the count as Sum
- 6. Filters do not count logs written before they were created
- 7. For JSON logs, take conditions and values from fields
- 8. Read counts split by dimension by specifying the dimension
- 9. Find the source filter from a metric
Start the emulator and point the AWS CLI at it
Install AWS Emulator by following the official Linux instructions. Start it with aws-emulator. The -t off option turns telemetry off.
aws-emulator -t off
Leave the emulator running, open another terminal, and set the environment variables from the official documentation. These send AWS CLI requests to the emulator and use its credentials.
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
Prepare a script to write logs
You write logs with aws logs put-log-events. In the test environment, passing JSON messages to --log-events in the short timestamp=...,message=... form failed with Error parsing parameter '--log-events'. So I wrote a script that takes messages, wraps each one as a log event with the current time, and writes them as a JSON array. It uses jq. Save it to a file and run chmod +x put-logs.sh to make it executable.
#!/bin/bash
# Usage: ./put-logs.sh log-group log-stream message...
# Write the messages together as log events timestamped now
group=$1 stream=$2; shift 2
now=$(date +%s%3N)
events=$(printf '%s\n' "$@" | jq -R --argjson t "$now" '{timestamp: $t, message: .}' | jq -s -c .)
aws logs put-log-events --log-group-name "$group" --log-stream-name "$stream" \
--log-events "$events" --query rejectedLogEventsInfo
The null in the output means no rejectedLogEventsInfo was returned, so no events were rejected.
Create the log group /example/app and the log stream web-1. Before creating the metric filter, write one ERROR log event. I check later whether it gets counted.
$ aws logs create-log-group --log-group-name /example/app
$ aws logs create-log-stream --log-group-name /example/app --log-stream-name web-1
$ ./put-logs.sh /example/app web-1 "ERROR before filter"
null
Check the pattern with test-metric-filter first
You can check a filter pattern for a metric filter against sample messages with aws logs test-metric-filter. According to the TestMetricFilter API reference, one request can include up to 50 messages. The request does not take a log group. You pass only the filter pattern and the messages.
$ aws logs test-metric-filter --filter-pattern ERROR --log-event-messages 'INFO start' 'ERROR db timeout' 'WARN slow' 'ERROR disk full'
{
"matches": [
{
"eventNumber": 2,
"eventMessage": "ERROR db timeout",
"extractedValues": {}
},
{
"eventNumber": 4,
"eventMessage": "ERROR disk full",
"extractedValues": {}
}
]
}
Two of the four messages contain ERROR, and both matched. eventNumber is the position of the message in the input. In the emulator, numbering started at 1. The example in the API reference numbers the first message as 0.
Create a filter with put-metric-filter
Create the filter with aws logs put-metric-filter. In --metric-transformations, specify the metric that receives the count.
$ aws logs put-metric-filter --log-group-name /example/app --filter-name error-count --filter-pattern ERROR --metric-transformations metricName=ErrorCount,metricNamespace=Example/App,metricValue=1,defaultValue=0,unit=Count
According to the MetricTransformation API reference, each field means the following.
| Field | Meaning | Value here |
|---|---|---|
metricNamespace, metricName |
The namespace and name of the metric that receives the result | Example/App, ErrorCount |
metricValue |
The value sent for each log event that matches the pattern | 1 |
defaultValue |
The value sent when the pattern does not match (optional) | 0 |
unit |
The metric unit. Defaults to None if omitted |
Count |
Since we are counting, we send 1 for each matching log event. Check the filter with describe-metric-filters.
$ aws logs describe-metric-filters --log-group-name /example/app
{
"metricFilters": [
{
"filterName": "error-count",
"filterPattern": "ERROR",
"metricTransformations": [
{
"metricName": "ErrorCount",
"metricNamespace": "Example/App",
"metricValue": "1",
"defaultValue": 0.0,
"unit": "Count"
}
],
"creationTime": 1795840387555,
"logGroupName": "/example/app",
"applyOnTransformedLogs": false
}
]
}
Write logs and read the count as Sum
After the filter is created, write the same four messages as before.
$ ./put-logs.sh /example/app web-1 "INFO start" "ERROR db timeout" "WARN slow" "ERROR disk full"
null
On the metric side, ErrorCount now exists in the Example/App namespace.
$ aws cloudwatch list-metrics --namespace Example/App
{
"Metrics": [
{
"Namespace": "Example/App",
"MetricName": "ErrorCount",
"Dimensions": []
}
]
}
Retrieve the values with aws cloudwatch get-metric-statistics. This command covers from 10 minutes ago to 5 minutes from now, grouped in 5-minute (300-second) periods.
$ aws cloudwatch get-metric-statistics --namespace Example/App --metric-name ErrorCount --start-time $(date -u -d "-10 min" +%FT%TZ) --end-time $(date -u -d "+5 min" +%FT%TZ) --period 300 --statistics Sum SampleCount
{
"Label": "ErrorCount",
"Datapoints": [
{
"Timestamp": "2026-11-28T04:33:00+00:00",
"SampleCount": 4.0,
"Sum": 2.0,
"Unit": "Count"
}
]
}
The Sum of 2 is the number of ERROR log events. SampleCount is 4. The two non-ERROR events were also sent, with the default value 0, so they are included in the count. To read the number of matches, use Sum, not SampleCount.

The filter pattern syntax for metric filters page describes the default value as the value sent for each minute in which no matching log events occur. It also says CloudWatch aggregates values per minute. In the emulator, 0 was recorded for each non-matching log event.
Filters do not count logs written before they were created
Sum is 2, and it does not include ERROR before filter, which was written before the filter existed. The log event itself is still in the log group. A filter-log-events search finds three matches.
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern ERROR --query "events[].message"
[
"ERROR before filter",
"ERROR db timeout",
"ERROR disk full"
]
The metric filter overview page also says that filters do not look back at existing data. A metric is sent only for log events that arrive after the filter is created.
A metric filter counts events as they arrive. In tests, create the filter first, then write the logs. To count logs that already exist, use filter-log-events or Logs Insights. (I tested this in How to search CloudWatch Logs with AWS Emulator.)
For JSON logs, take conditions and values from fields
If your logs are JSON, you can write a condition such as { $.status >= 500 } in the filter pattern. Create the log group /example/api and the log stream api-1, and check the pattern with test-metric-filter first.
$ aws logs create-log-group --log-group-name /example/api
$ aws logs create-log-stream --log-group-name /example/api --log-stream-name api-1
$ aws logs test-metric-filter --filter-pattern '{ $.status >= 500 }' --log-event-messages '{"status":200,"path":"/orders","ms":35}' '{"status":503,"path":"/orders","ms":2400}'
{
"matches": [
{
"eventNumber": 2,
"eventMessage": "{\"status\":503,\"path\":\"/orders\",\"ms\":2400}",
"extractedValues": {
"$.path": "/orders",
"$.ms": "2400",
"$.status": "503"
}
}
]
}
Only the event with status 503 matched. extractedValues shows the fields extracted from the log.
Next, create three filters. The first counts 5xx responses. The second uses the response time ms field as the value. The third counts responses with status 400 or higher, grouped by path.
$ aws logs put-metric-filter --log-group-name /example/api --filter-name server-errors --filter-pattern '{ $.status >= 500 }' --metric-transformations metricName=ServerErrors,metricNamespace=Example/Api,metricValue=1,defaultValue=0,unit=Count
$ aws logs put-metric-filter --log-group-name /example/api --filter-name latency --filter-pattern '{ $.ms = * }' --metric-transformations 'metricName=Latency,metricNamespace=Example/Api,metricValue=$.ms,unit=Milliseconds'
In the second filter, setting metricValue to $.ms sends the numeric value from the log instead of 1. This matches the form of the { $.latency = * } example with $.latency in the filter pattern syntax page. The values are wrapped in single quotes so the shell does not expand $.
In the third filter, the dimension
Path takes its value from $.path. I first added defaultValue=0 as in the first filter, which caused an error.
$ aws logs put-metric-filter --log-group-name /example/api --filter-name errors-by-path --filter-pattern '{ $.status >= 400 }' --metric-transformations 'metricName=ErrorsByPath,metricNamespace=Example/Api,metricValue=1,defaultValue=0,dimensions={Path=$.path}'
aws: [ERROR]: An error occurred (InvalidParameterException) when calling the PutMetricFilter operation: Invalid metric transformation: dimensions and default value are mutually exclusive properties
The metric filter overview page also says that a metric with dimensions cannot have a default value. After I removed defaultValue, the filter was created.
$ aws logs put-metric-filter --log-group-name /example/api --filter-name errors-by-path --filter-pattern '{ $.status >= 400 }' --metric-transformations 'metricName=ErrorsByPath,metricNamespace=Example/Api,metricValue=1,unit=Count,dimensions={Path=$.path}'
Write four log events. Two have 5xx status, three have status 400 or higher, and two of those three have path set to /users.
$ ./put-logs.sh /example/api api-1 '{"level":"INFO","status":200,"path":"/orders","ms":35}' '{"level":"ERROR","status":503,"path":"/orders","ms":2400}' '{"level":"WARN","status":429,"path":"/users","ms":5}' '{"level":"ERROR","status":500,"path":"/users","ms":800}'
null
In the commands below, --start-time and --end-time come from date -u -d "-10 min" +%FT%TZ and date -u -d "+5 min" +%FT%TZ, as before. The values in the examples are from the run, so they are 10 minutes before and 5 minutes after that run. When you run these yourself, use the $(date ...) form from the first example, or replace the times with ones that match your run.
The Sum for 5xx responses is 2.
$ aws cloudwatch get-metric-statistics --namespace Example/Api --metric-name ServerErrors --start-time 2026-11-28T04:23:21Z --end-time 2026-11-28T04:38:21Z --period 300 --statistics Sum SampleCount
{
"Label": "ServerErrors",
"Datapoints": [
{
"Timestamp": "2026-11-28T04:33:00+00:00",
"SampleCount": 4.0,
"Sum": 2.0,
"Unit": "Count"
}
]
}
For response times, the ms values from the four events were recorded as values. The average is 810 and the maximum is 2400, which you can read without re-aggregating the logs. All four events have ms, so SampleCount is 4.
$ aws cloudwatch get-metric-statistics --namespace Example/Api --metric-name Latency --start-time 2026-11-28T04:23:21Z --end-time 2026-11-28T04:38:21Z --period 300 --statistics Sum Average Maximum SampleCount
{
"Label": "Latency",
"Datapoints": [
{
"Timestamp": "2026-11-28T04:33:00+00:00",
"SampleCount": 4.0,
"Average": 810.0,
"Sum": 3240.0,
"Maximum": 2400.0,
"Unit": "Milliseconds"
}
]
}
Read counts split by dimension by specifying the dimension
ErrorsByPath created a separate metric for each path value.
$ aws cloudwatch list-metrics --namespace Example/Api --metric-name ErrorsByPath --query "Metrics[].Dimensions[]" --output text
Path /orders
Path /users
Specifying /users with --dimensions returns the count of 2.
$ aws cloudwatch get-metric-statistics --namespace Example/Api --metric-name ErrorsByPath --dimensions Name=Path,Value=/users --start-time 2026-11-28T04:23:21Z --end-time 2026-11-28T04:38:21Z --period 300 --statistics Sum
{
"Label": "ErrorsByPath",
"Datapoints": [
{
"Timestamp": "2026-11-28T04:33:00+00:00",
"Sum": 2.0,
"Unit": "Count"
}
]
}
Without a dimension, the request did not return an error. It returned an empty result. It did not return the total across all path values.
$ aws cloudwatch get-metric-statistics --namespace Example/Api --metric-name ErrorsByPath --start-time 2026-11-28T04:23:21Z --end-time 2026-11-28T04:38:21Z --period 300 --statistics Sum
{
"Label": "ErrorsByPath",
"Datapoints": []
}
The CloudWatch metric concepts page explains that each combination of dimension values is a separate metric, and you can retrieve statistics only for the exact combination that was sent. If you also need the overall total, create a separate filter without dimensions, such as ServerErrors in this example, and read it directly.
According to the MetricTransformation API reference, in real CloudWatch, metrics created from logs are charged as custom metrics. Each dimension value counts as a separate metric. Avoid using fields with many distinct values, such as IP addresses or request IDs, as dimensions. A single filter can have up to three dimensions. In the emulator, adding four dimensions returned InvalidParameterException.
Find the source filter from a metric
When you know the metric name, for example from an alarm, and want to find which log group and filter produced it, pass the metric namespace and name to describe-metric-filters.
$ aws logs describe-metric-filters --metric-namespace Example/Api --metric-name Latency --query "metricFilters[].[logGroupName,filterName,filterPattern]" --output text
/example/api latency { $.ms = * }
ErrorCount and ServerErrors created here are regular CloudWatch metrics, so you can use them for alarms that notify you when a threshold is crossed. For how to create the alarm, see How to test CloudWatch alarms with AWS Emulator, which uses custom metrics.





