日本語

How to Search CloudWatch Logs with AWS Emulator

​​AWS Emulator​Amazon CloudWatch Logs,AWS CLI

With AWS Emulator running locally, you can write logs to CloudWatch Logs and search them with the AWS CLI, without an AWS account. This is the procedure for trying out a process that finds error logs in CloudWatch Logs, or a Logs Insights aggregation query that counts log entries, in a local environment or CI without real logs. It covers everything from creating a log group and writing logs, to searching with filter patterns, running CloudWatch Logs Insights queries, and displaying output with aws logs tail. The commands and output shown are exactly what I ran in the test environment.

Note

The test environment was Ubuntu 24.04 (x86_64), AWS Emulator 1.0.486 (released November 17, 2026), AWS CLI 2.40.4, and jq 1.7. I did not use an AWS account or credentials. I did not verify how things behave on real CloudWatch Logs: pricing, deletion of logs past their retention period, permission checks, or how long queries take. I did not test the aws logs tail --follow usage that waits for new logs, or how filter patterns that mix ?-prefixed terms with other terms behave on real CloudWatch Logs. Where I describe real AWS behavior, I am relying on the official documentation. The 12-digit account ID in the output has been replaced.

Start the emulator and point the AWS CLI at it

AWS Emulator is an emulator that accepts AWS API calls locally. According to the official documentation, no AWS account is needed, and requests are not sent to AWS.

For installation, see the separate article "How to install and start using AWS Emulator on Ubuntu." Here I installed the Debian package from the Linux instructions after verifying its gpg signature. I worked as root, so I did not use sudo, but the commands below include it for a regular user.

bash
curl -fsSLO https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator_amd64.deb
sudo apt-get install -y ./aws-emulator_amd64.deb

Start it with aws-emulator. -t off disables the usage data sent to AWS by default (telemetry). The emulator keeps running on that terminal, so use the AWS CLI from another terminal.

bash
aws-emulator -t off

In another terminal, set the environment variables from the official documentation. The emulator listens on 127.0.0.1:9297 and writes an access key, a config file, and a certificate valid only for this run to ~/.aws/emulator/9297/.

bash
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
Warning

The official documentation warns that if you run a command in a shell where AWS_ENDPOINT_URL is not set, it will be sent to real AWS using whatever credentials are found. On a machine with real credentials, run these commands only in a shell where all the environment variables above are set.

If the ARN ends in user/emulator, the emulator is responding. Right after startup, there are no log groups.

text
$ aws sts get-caller-identity --query Arn --output text
arn:aws:iam::<12桁のアカウントID>:user/emulator
$ aws logs describe-log-groups
{
    "logGroups": []
}

Create a log group and log streams

CloudWatch Logs stores logs in three levels: log groups, log streams, and log events. According to the official glossary, a log event is a pair of a timestamp and a message, and a log stream is a sequence of log events from the same source (such as one application instance). A log group is a container for log streams that holds shared settings such as retention.

Here I created the log streams web-1 and web-2 inside the log group /example/app, representing two web servers.

text
$ 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
$ aws logs create-log-stream --log-group-name /example/app --log-stream-name web-2

None of these commands printed anything on success (the exit code was 0). You can confirm what was created with describe-log-groups and describe-log-streams. If you do not specify a retention period, retentionInDays was null.

text
$ aws logs describe-log-groups --query "logGroups[].{name: logGroupName, retention: retentionInDays, bytes: storedBytes}"
[
    {
        "name": "/example/app",
        "retention": null,
        "bytes": 0
    }
]
$ aws logs describe-log-streams --log-group-name /example/app --query "logStreams[].logStreamName"
[
    "web-1",
    "web-2"
]

Creating a log group with the same name again was rejected with ResourceAlreadyExistsException. If a test setup creates it every time, you need to either ignore this error or delete the group beforehand.

text
$ aws logs create-log-group --log-group-name /example/app

aws: [ERROR]: An error occurred (ResourceAlreadyExistsException) when calling the CreateLogGroup operation: The specified log group already exists

Write logs

Logs are written with aws logs put-log-events. Each log event is a pair of timestamp (milliseconds since January 1, 1970) and message. In a shell, date +%s%3N gives the current time in milliseconds.

text
$ date +%s%3N
1794899351146

When there are only a few events, listing them in --log-events as timestamp=...,message=... is quick.

text
$ T=$(date +%s%3N); aws logs put-log-events --log-group-name /example/app --log-stream-name web-1 --log-events timestamp=$T,message="INFO server started" timestamp=$((T+1)),message="ERROR db timeout after 3000 ms"
{
    "nextSequenceToken": "00000000000000000000000000000000000000000000000000000002"
}

When messages contain quotation marks, as with JSON logs, it is easier to put the array of log events in a JSON file and pass it with file://. Below, I used jq to create events.json, in which each message is a JSON string, and wrote it to web-2.

text
$ T=$(date +%s%3N); jq -n -c --argjson t $T '[{timestamp:$t,message:({level:"ERROR",status:500,path:"/api/orders",ms:1200}|tojson)},{timestamp:($t+1),message:({level:"INFO",status:200,path:"/api/orders",ms:35}|tojson)},{timestamp:($t+2),message:({level:"WARN",status:429,path:"/api/users",ms:5}|tojson)}]' > events.json; cat events.json
[{"timestamp":1794899351760,"message":"{\"level\":\"ERROR\",\"status\":500,\"path\":\"/api/orders\",\"ms\":1200}"},{"timestamp":1794899351761,"message":"{\"level\":\"INFO\",\"status\":200,\"path\":\"/api/orders\",\"ms\":35}"},{"timestamp":1794899351762,"message":"{\"level\":\"WARN\",\"status\":429,\"path\":\"/api/users\",\"ms\":5}"}]
$ aws logs put-log-events --log-group-name /example/app --log-stream-name web-2 --log-events file://events.json
{
    "nextSequenceToken": "00000000000000000000000000000000000000000000000000000006"
}

The figure below shows where the logs in this article are stored. It also indicates which part of the log group each search command reads.

Log group /example/app contains log stream web-1 (text logs) and web-2 (JSON logs). get-log-events reads one stream, while filter-log-events, tail, and start-query read the whole group. The labels in this image are in Japanese.
The log group created in this article and the range each command reads

When logs you wrote do not appear

put-log-events may succeed without error even when some log events do not meet the conditions. The PutLogEvents API reference states that events older than 14 days and events more than 2 hours in the future are rejected while the other valid events are still processed.

In the emulator, when I wrote a log from 15 days ago and a current log in one call, the exit code was 0, but the response included rejectedLogEventsInfo. The same happened when I wrote a log 3 hours in the future along with a current log.

text
$ T=$(date +%s%3N); aws logs put-log-events --log-group-name /example/app --log-stream-name web-1 --log-events timestamp=$((T-15*24*3600*1000)),message="INFO 15 days ago" timestamp=$T,message="INFO now"
{
    "nextSequenceToken": "00000000000000000000000000000000000000000000000000000008",
    "rejectedLogEventsInfo": {
        "tooOldLogEventEndIndex": 1
    }
}
$ T=$(date +%s%3N); aws logs put-log-events --log-group-name /example/app --log-stream-name web-1 --log-events timestamp=$T,message="INFO now 2" timestamp=$((T+3*3600*1000)),message="INFO 3 hours later"
{
    "nextSequenceToken": "00000000000000000000000000000000000000000000000000000010",
    "rejectedLogEventsInfo": {
        "tooNewLogEventStartIndex": 1
    }
}

The numbers are positions (counted from 0) in the array sent. According to the RejectedLogEventsInfo description, tooOldLogEventEndIndex means everything before that index (the index itself not included) is too old, and tooNewLogEventStartIndex means everything from that index onward is too new. In the first call, the rejected event was index 0, "INFO 15 days ago." In the second, it was index 1, "INFO 3 hours later." Only the current logs remained in web-1.

text
$ aws logs filter-log-events --log-group-name /example/app --log-stream-names web-1 --query "events[].message"
[
    "INFO server started",
    "ERROR db timeout after 3000 ms",
    "INFO now",
    "INFO now 2"
]

In tests that write a batch of old logs, do not treat the exit code alone as success. Check whether rejectedLogEventsInfo is present.

On the other hand, put-log-events itself failed when the events in one call were not in chronological order, and when the log stream did not exist. The exit code was 254.

text
$ T=$(date +%s%3N); aws logs put-log-events --log-group-name /example/app --log-stream-name web-1 --log-events timestamp=$((T+10)),message="b" timestamp=$T,message="a"

aws: [ERROR]: An error occurred (InvalidParameterException) when calling the PutLogEvents operation: Log events in a single PutLogEvents request must be in chronological order.
$ T=$(date +%s%3N); aws logs put-log-events --log-group-name /example/app --log-stream-name web-9 --log-events timestamp=$T,message="x"

aws: [ERROR]: An error occurred (ResourceNotFoundException) when calling the PutLogEvents operation: The specified log stream does not exist.

The API reference also lists the chronological ordering requirement as a condition.

Conversely, some incorrect values are accepted. The nextSequenceToken in the put-log-events response no longer needs to be used. According to the same API reference, sequence tokens are now ignored, and an incorrect token is accepted. In the emulator, a write with a made-up --sequence-token 123 also went through.

text
$ T=$(date +%s%3N); aws logs put-log-events --log-group-name /example/app --log-stream-name web-1 --sequence-token 123 --log-events timestamp=$T,message="INFO wrong token"
{
    "nextSequenceToken": "00000000000000000000000000000000000000000000000000000012"
}

Read one log stream in order

To read a specific log stream from oldest to newest, use aws logs get-log-events with --start-from-head. The results show the timestamp given to the log (timestamp) next to the time CloudWatch Logs accepted it (ingestionTime).

text
$ aws logs get-log-events --log-group-name /example/app --log-stream-name web-1 --start-from-head
{
    "events": [
        {
            "timestamp": 1794899351149,
            "message": "INFO server started",
            "ingestionTime": 1794899351640
        },
        {
            "timestamp": 1794899351150,
            "message": "ERROR db timeout after 3000 ms",
            "ingestionTime": 1794899351640
        },
        {
            "timestamp": 1794899352476,
            "message": "INFO now",
            "ingestionTime": 1794899352975
        },
        {
            "timestamp": 1794899353104,
            "message": "INFO now 2",
            "ingestionTime": 1794899353685
        },
        {
            "timestamp": 1794899355923,
            "message": "INFO wrong token",
            "ingestionTime": 1794899356468
        }
    ],
    "nextForwardToken": "f/20000000000000000000000000001794899355923000000116942627/s",
    "nextBackwardToken": "b/20000000000000000000000000001794899351149000000006942627/s"
}

Search the whole group with a filter pattern

To search across all log streams in a log group, use aws logs filter-log-events. The value passed to --filter-pattern is a CloudWatch Logs filter pattern.

The simplest form is a single term. Searching for ERROR found both the text log in web-1 and the JSON log in web-2.

text
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern ERROR --query "events[].[logStreamName, message]" --output text
web-1	ERROR db timeout after 3000 ms
web-2	{"level":"ERROR","status":500,"path":"/api/orders","ms":1200}

Filter patterns are case-sensitive (the official documentation says so too). Searching for lowercase error found nothing.

text
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern error --query "events[].message"
[]

Narrowing with combinations of terms

To search for a phrase containing spaces, enclose it in double quotes. Putting - before a term excludes logs that contain it.

text
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern "\"db timeout\"" --query "events[].message"
[
    "ERROR db timeout after 3000 ms"
]
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern "ERROR -db" --query "events[].message"
[
    "{\"level\":\"ERROR\",\"status\":500,\"path\":\"/api/orders\",\"ms\":1200}"
]

For "contains any one of these," put ? before each term. ?ERROR ?WARN found three entries containing either ERROR or WARN.

text
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern "?ERROR ?WARN" --query "events[].message"
[
    "ERROR db timeout after 3000 ms",
    "{\"level\":\"ERROR\",\"status\":500,\"path\":\"/api/orders\",\"ms\":1200}",
    "{\"level\":\"WARN\",\"status\":429,\"path\":\"/api/users\",\"ms\":5}"
]

This is where the emulator's results did not match the official documentation. The documentation says that when ? terms are mixed into a pattern with terms that have no ?, all the ? terms are ignored. In other words, ?ERROR ?WARN orders should give the same result as a pattern containing only orders.

I restarted the emulator, wrote only the same three entries to web-2, and compared. orders alone returned two entries (the ERROR and INFO lines). ?ERROR ?WARN orders returned only one entry, the one that contains both ERROR and orders. The emulator is not ignoring the ? terms.

text
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern "orders" --query "events[].message"
[
    "{\"level\":\"ERROR\",\"status\":500,\"path\":\"/api/orders\",\"ms\":1200}",
    "{\"level\":\"INFO\",\"status\":200,\"path\":\"/api/orders\",\"ms\":35}"
]
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern "?ERROR ?WARN orders" --query "events[].message"
[
    "{\"level\":\"ERROR\",\"status\":500,\"path\":\"/api/orders\",\"ms\":1200}"
]

Since the emulator and the official documentation disagree on patterns that mix ? terms with other terms, it is safer not to rely on them in tests or in production searches.

Filtering JSON logs by field values

For logs whose message is JSON, you can filter on field values using the form { $.fieldName operator value }. Numbers can be compared with operators such as >=, and conditions can be combined with &&. String values are enclosed in double quotes.

text
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern "{ \$.status >= 500 }" --query "events[].message"
[
    "{\"level\":\"ERROR\",\"status\":500,\"path\":\"/api/orders\",\"ms\":1200}"
]
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern "{ \$.path = \"/api/orders\" && \$.ms > 100 }" --query "events[].message"
[
    "{\"level\":\"ERROR\",\"status\":500,\"path\":\"/api/orders\",\"ms\":1200}"
]
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern "{ \$.level = \"INFO\" }" --query "events[].message"
[
    "{\"level\":\"INFO\",\"status\":200,\"path\":\"/api/orders\",\"ms\":35}"
]

Because these are written inside double quotes in the shell, a \ is placed before each $. Without it, the shell would try to read $.status as a variable.

Searching with regular expressions

Enclosing a pattern in % lets you search with a regular expression. According to the official documentation, only a limited set of symbols is supported, the list does not include whitespace, and grouping with ( and ) is not supported. For whitespace, use \s, which is in the list. When I searched for logs where four digits are followed by a space and "ms", the entry containing 3000 ms was found. (I verified this with only the two web-1 entries written.)

text
$ aws logs filter-log-events --log-group-name /example/app --filter-pattern "%[0-9]{4}\sms%" --query "events[].message"
[
    "ERROR db timeout after 3000 ms"
]

Narrowing by log stream and time

Adding --log-stream-name-prefix searches only log streams whose names start with the given string. To list specific names, use --log-stream-names.

text
$ aws logs filter-log-events --log-group-name /example/app --log-stream-name-prefix web-2 --filter-pattern ERROR --query "events[].message"
[
    "{\"level\":\"ERROR\",\"status\":500,\"path\":\"/api/orders\",\"ms\":1200}"
]

--start-time takes a time in milliseconds. Below, I stored the current time in variable T, waited 2 seconds, wrote one log entry, and then searched for ERROR entries after T. ERROR logs written before that point do not appear. This is useful in tests that need to confirm only the logs produced after a given operation.

text
$ T=$(date +%s%3N); sleep 2; aws logs put-log-events --log-group-name /example/app --log-stream-name web-1 --log-events timestamp=$(date +%s%3N),message="ERROR after mark" >/dev/null; aws logs filter-log-events --log-group-name /example/app --start-time $T --filter-pattern ERROR --query "events[].message"
[
    "ERROR after mark"
]

According to the FilterLogEvents API reference, on real CloudWatch Logs, results may be split across multiple pages, and an intermediate page can be empty. Whether there are more results is determined by whether nextToken is present. At this volume, the emulator's response did not include nextToken.

Aggregate with Logs Insights queries

When you want counts or averages, use a CloudWatch Logs Insights query. In the AWS CLI, start a query with aws logs start-query, then pass the returned queryId to aws logs get-query-results to receive the results. As stated in the StartQuery API reference, --start-time and --end-time take seconds, not milliseconds. Be careful, since this differs from filter-log-events.

Typing both commands each time is tedious, so I put them in the following script, insights.sh. It runs a query over the last hour of logs, waits until the status becomes Complete (checking once per second), and then prints the results.

bash
#!/bin/bash
# Usage: bash insights.sh 'query' ['JMESPath' [other AWS CLI options]]
# Runs a CloudWatch Logs Insights query over the last hour of /example/app, waits for it to finish, and prints the results
Q=$(aws logs start-query --log-group-name /example/app \
  --start-time $(date -d '-1 hour' +%s) --end-time $(date +%s) \
  --query-string "$1" --query queryId --output text)
for i in $(seq 30); do
  S=$(aws logs get-query-results --query-id "$Q" --query status --output text)
  [ "$S" = Complete ] && break
  sleep 1
done
aws logs get-query-results --query-id "$Q" --query "${2:-results}" "${@:3}"

First, I listed the logs containing ERROR, newest first. Results come back as arrays of field and value pairs per row, so I used JMESPath to extract just the log stream name and the message.

text
$ bash insights.sh "fields @timestamp, @logStream, @message | filter @message like /ERROR/ | sort @timestamp desc | limit 5" "results[*].[ @[?field==\`@logStream\`].value | [0], @[?field==\`@message\`].value | [0] ]" --output text
web-1	ERROR after mark
web-2	{"level":"ERROR","status":500,"path":"/api/orders","ms":1200}
web-1	ERROR db timeout after 3000 ms

@message and @logStream are fields that Logs Insights provides for every log. According to the explanation of automatically discovered fields, for JSON logs, fields inside the JSON can also be used in queries. In the emulator, I could use status, ms, and path directly. The query below keeps only logs that have a status field (the JSON logs), then gives the count per path and the average ms. The results are shown unmodified.

text
$ bash insights.sh "filter ispresent(status) | stats count(*) as n, avg(ms) as avg_ms by path"
[
    [
        {
            "field": "path",
            "value": "/api/orders"
        },
        {
            "field": "n",
            "value": "2"
        },
        {
            "field": "avg_ms",
            "value": "617.5"
        }
    ],
    [
        {
            "field": "path",
            "value": "/api/users"
        },
        {
            "field": "n",
            "value": "1"
        },
        {
            "field": "avg_ms",
            "value": "5"
        }
    ]
]

Values are numeric, but they came back as strings such as "2" and "617.5". When comparing them as numbers in tests, convert them first.

JSON fields can also be used in filter conditions. Two logs with status of 400 or higher were returned.

text
$ bash insights.sh "fields @message | filter status >= 400" "results[*][?field==\`@message\`].value[]"
[
    "{\"level\":\"WARN\",\"status\":429,\"path\":\"/api/users\",\"ms\":5}",
    "{\"level\":\"ERROR\",\"status\":500,\"path\":\"/api/orders\",\"ms\":1200}"
]

The query syntax documentation recommends narrowing the log groups and time range as much as possible so that large queries on real CloudWatch Logs do not run up charges. The emulator does not charge, but if you plan to use the same query in production, it is safer to write it with a narrow scope from the start.

Stream logs to the terminal with aws logs tail

If you just want to follow logs by eye, aws logs tail is convenient. It prints one line per log entry from all log streams in the group, with the time and stream name. According to the tail reference, by default it shows logs from the last 10 minutes and then exits. --since 1h shows logs from the last hour, and --filter-pattern accepted a filter pattern as written.

text
$ timeout 10 aws logs tail /example/app --since 1h --filter-pattern "{ \$.status >= 400 }"
2026-11-17T07:09:11.760000+00:00 web-2 {"level":"ERROR","status":500,"path":"/api/orders","ms":1200}
2026-11-17T07:09:11.762000+00:00 web-2 {"level":"WARN","status":429,"path":"/api/users","ms":5}

With --format short, the stream name is omitted and the time is shortened to seconds. All the logs written in this article appeared in chronological order. (The timeout 10 at the start was added to keep the verification script from hanging. According to the tail reference, without --follow, the command exits once there are no more logs to show.)

text
$ timeout 10 aws logs tail /example/app --since 1h --format short
2026-11-17T07:09:11 INFO server started
2026-11-17T07:09:11 ERROR db timeout after 3000 ms
2026-11-17T07:09:11 {"level":"ERROR","status":500,"path":"/api/orders","ms":1200}
2026-11-17T07:09:11 {"level":"INFO","status":200,"path":"/api/orders","ms":35}
2026-11-17T07:09:11 {"level":"WARN","status":429,"path":"/api/users","ms":5}
2026-11-17T07:09:12 INFO now
2026-11-17T07:09:13 INFO now 2
2026-11-17T07:09:15 INFO wrong token
2026-11-17T07:09:27 ERROR after mark

Cleanup

When you are done testing, delete the log group with aws logs delete-log-group. The list went back to empty.

text
$ aws logs delete-log-group --log-group-name /example/app
$ aws logs describe-log-groups --query "logGroups[].logGroupName"
[]

According to the limitations description, the emulator keeps everything in memory and discards it when stopped. If you restart the emulator for each test run, you can start from a clean state without a step to delete log groups.

​Posted by 86