Sub topic 9
Sending container logs to CloudWatch Logs
This chapter assumes you can read a Fargate task definition, know what an IAM role and a trust policy are, and have used the AWS CLI. You should also know that a container writes logs to standard output (stdout) and standard error (stderr).
How logs leave a Fargate task
On Fargate you cannot log in to the host and read files under /var/log. The platform gives you a log driver instead. A log driver is a component that captures each container's stdout and stderr and sends them somewhere else. The awslogs driver sends them to Amazon CloudWatch Logs.
This has one practical consequence for your application: write logs to stdout and stderr, not to a file inside the container. A log file in the container's writable layer is not collected by awslogs. It disappears when the task stops.
The logConfiguration block
You enable logging per container, inside containerDefinitions. This is the block from the task definition used throughout this tutorial:
{
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/web-app",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "web"
}
}
}The three options work like this:
| Option | Meaning |
|---|---|
| `awslogs-group` | The log group that receives the logs. A log group is a container for log streams that share retention and access settings. |
| `awslogs-region` | The Region of the log group. It is normally the Region where the task runs. |
| `awslogs-stream-prefix` | A prefix for the log stream name. Required on Fargate. |
With a prefix, the log stream name has this form:
prefix-name/container-name/ecs-task-idFor the task definition above, a stream might be named web/web/0f3a9c1d2b8e4c7aa1b2c3d4e5f60718. Each task gets its own stream, and the task ID in the name lets you match a stream to a task shown in the ECS console or in aws ecs list-tasks.
Permissions: the task execution role does the writing
Log delivery is done by the ECS agent on behalf of your task, not by your application code. For that reason the permission belongs to the task execution role, not the task role. If you are unsure of the difference, the earlier chapter on the two roles covers it.
The managed policy AmazonECSTaskExecutionRolePolicy includes these actions:
logs:CreateLogStreamlogs:PutLogEvents
The execution role must also trust ecs-tasks.amazonaws.com, using the trust policy shown earlier in this tutorial.
The managed policy does not include logs:CreateLogGroup. That leads to the most common logging failure, covered next.
Creating the log group
You have two choices. Pick one and stay with it.
Option 1: create the group yourself
This is the recommended approach. You control the retention period and can add tags and encryption.
aws logs create-log-group --log-group-name /ecs/web-app --region us-east-1
aws logs put-retention-policy \
--log-group-name /ecs/web-app \
--retention-in-days 30 \
--region us-east-1Log groups created by hand or by ECS default to never expiring. Logs then accumulate and you pay for storage indefinitely. Setting a retention period is the cheapest cost control in this chapter.
Option 2: let ECS create the group
Add awslogs-create-group to the options:
{
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/web-app",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "web",
"awslogs-create-group": "true"
}
}
}This only works if the execution role is also allowed logs:CreateLogGroup. Add an inline policy like this one:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/ecs/web-app"
}
]
}The group that ECS creates has no retention limit, so you still need to call put-retention-policy afterward.
Reading logs
Use aws logs tail to follow logs from the terminal. This is the quickest way to see what a new deployment is doing.
aws logs tail /ecs/web-app --follow --since 15m --region us-east-1To read only one container's streams, filter by stream prefix:
aws logs tail /ecs/web-app --log-stream-name-prefix web/web --follow --region us-east-1For searching across many tasks, use CloudWatch Logs Insights. A query that returns recent error lines looks like this:
fields @timestamp, @logStream, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 50Structured logs
Plain text lines are hard to query. If your application writes one JSON object per line, Logs Insights discovers the fields automatically.
{"level":"error","msg":"db timeout","path":"/orders","ms":5012}Now you can filter on a field instead of matching text:
fields @timestamp, path, ms
| filter level = "error"
| stats count() by pathKeep each event on a single line. A multi-line stack trace is split into separate CloudWatch events, which makes it hard to read. The awslogs-multiline-pattern option can group lines that begin with a given pattern into one event, but emitting JSON is simpler and more reliable.
Delivery mode: blocking or non-blocking
By default the driver runs in blocking mode. If CloudWatch Logs is slow or unreachable, writes to stdout can block, and your application can stall while it waits to write a log line. You can switch a container to non-blocking mode:
{
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/web-app",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "web",
"mode": "non-blocking",
"max-buffer-size": "25m"
}
}
}In non-blocking mode, log lines go to an in-memory buffer of the size you set. If the buffer fills, new lines are dropped and the application keeps running. The trade-off is availability against completeness. Choose non-blocking for latency-sensitive services where losing a few lines is acceptable. Keep blocking where every line must be kept, such as audit logs.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Task stops at start with `ResourceInitializationError` mentioning the log group does not exist | The log group is missing and `awslogs-create-group` is not set | Create the group, or set the option and grant `logs:CreateLogGroup` |
| Same error, with a timeout | The task has no network route to CloudWatch Logs | Give private subnets a NAT gateway or a `logs` VPC interface endpoint |
| Task starts, but no logs appear | The app writes to a file, or the group or Region in the options is wrong | Log to stdout and check `awslogs-group` and `awslogs-region` |
| `AccessDeniedException` on `PutLogEvents` | The execution role lacks permission, or the task role was edited by mistake | Attach `AmazonECSTaskExecutionRolePolicy` to the execution role |
| Logs are one line per stack frame | Multi-line output | Emit JSON, or set `awslogs-multiline-pattern` |
The network failure is easy to miss. The task definition in this tutorial runs in private subnets with assignPublicIp=DISABLED. The driver needs to reach the CloudWatch Logs endpoint, so those subnets need a route through a NAT gateway or a VPC interface endpoint for com.amazonaws.us-east-1.logs.
You can read the stopped reason like this:
aws ecs describe-tasks \
--cluster demo \
--tasks <task-id> \
--query "tasks[0].{stopCode:stopCode,reason:stoppedReason}"Beyond awslogs
awslogs is the simplest choice and needs no extra containers. If you need to send logs to another destination, such as Amazon OpenSearch Service, Firehose, or a third-party tool, Fargate also supports the awsfirelens driver. It runs a Fluent Bit or Fluentd sidecar container in the task. A sidecar is a helper container that runs next to your main container. That sidecar uses part of your task's CPU and memory, so account for it when you size the task. This tutorial uses awslogs throughout.
Exercises
Exercise
A new Fargate task stops immediately and never starts your container. The stopped reason says the log group /ecs/web-app does not exist. The execution role has AmazonECSTaskExecutionRolePolicy attached. Give two ways to fix this.
Show answer
Either create the log group beforehand with aws logs create-log-group --log-group-name /ecs/web-app, or add "awslogs-create-group": "true" to the log options and grant the execution role logs:CreateLogGroup on that group, because the managed policy does not include it. Creating the group yourself is preferred because you can set retention at the same time.
Exercise
Your task runs in private subnets with no public IP, and it fails at startup with a timeout while setting up logging. The execution role is correct. What is the most likely cause, and what two network changes could solve it?
Show answer
The task cannot reach the CloudWatch Logs endpoint. Add a NAT gateway route for the private subnets, or create a VPC interface endpoint for the logs service (for example com.amazonaws.us-east-1.logs) and allow the task's security group to reach it on port 443.
Exercise
A latency-sensitive API sometimes stalls for seconds when CloudWatch Logs has a slow period. Which awslogs option changes this, and what do you give up?
Show answer
Set "mode": "non-blocking" with a max-buffer-size, such as 25m. Writes then go to an in-memory buffer and the application no longer waits on the log service. If the buffer fills, log lines are dropped, so you give up guaranteed delivery of every line.