CloudWatch, CloudTrail & AWS Config
Set up metrics, alarms, audit trails and compliance rules.
By Invicly Tech, , in AWS Solutions Architect – Associate. About 12 minutes to read.
In short
CloudWatch collects metrics and logs and raises alarms that trigger actions. CloudTrail records who called which AWS API and when. AWS Config records resource configuration over time and checks it against compliance rules.
Explained simply
Monitoring answers three different questions, and AWS has a service for each. Is my system healthy right now? That is CloudWatch, with metrics, logs and alarms. Who did what in my account? That is CloudTrail, a record of API calls. Is my setup still the way it should be? That is AWS Config.
A metric is a number measured over time, like CPU use every minute or the count of 5xx errors. An alarm watches one metric and changes state when it crosses a line for long enough. Alarms can send a message, scale a group of servers, or reboot or recover an instance.
Logs are the detailed story behind the numbers. CloudWatch Logs collects log lines from Lambda, containers, servers and many AWS services in one place. Logs Insights lets you search them with a short query language, for example to count errors per minute or find the slowest requests.
CloudTrail is the security camera of your account. Every console click and API call becomes an event: who, from where, when, and what. AWS Config takes snapshots of each resource's settings over time and checks them against rules, like every EBS volume must be encrypted.
Press Play on a diagram to walk through it one step at a time.
- Performance metrics
- Logs and Logs Insights
- Alarms and dashboards
- What is happening now
- API call history
- Who did what, when
- 90-day event history free
- Trails to S3 for longer
- Resource config history
- Compliance rules
- Auto remediation
- What changed and is it allowed
- 1Publish metric
Service or agent sends data points.
- 2Evaluate alarm
Threshold breached for N periods.
- 3Take action
Notify SNS, scale ASG or recover EC2.
- 4Return to OK
Metric recovers and alarm state resets.
- Back to step 1
- Engineer to Security group: Opens port 22 to 0.0.0.0/01Opens port 22 to 0.0.0.0/0
- Security group to AWS Config: Configuration change recorded2Configuration change recorded
- 3Rule restricted-ssh: NON_COMPLIANTAWS Config to AWS Config: Rule restricted-ssh: NON_COMPLIANT
- AWS Config to SSM Automation: Run remediation document4Run remediation document
- SSM Automation to Security group: Remove the open SSH rule5Remove the open SSH rule
- 6Re-evaluate: COMPLIANTAWS Config to AWS Config: Re-evaluate: COMPLIANT
- Is it healthy now?
- CloudWatch metrics and alarms
- What went wrong inside the app?
- CloudWatch Logs and Logs Insights
- X-Ray traces for request paths
- Who made this change?
- CloudTrail event history or trail
- What did this resource look like before?
- AWS Config timeline
- Are we following our rules?
- Config rules and conformance packs
- React to an API call right away
- EventBridge rule on CloudTrail events
In depth
Metrics: resolution, retention and the agent
AWS services publish metrics to CloudWatch automatically. EC2 sends them every 5 minutes for free (basic monitoring) or every minute with detailed monitoring for a fee. Custom metrics can be standard resolution (1 minute) or high resolution (down to 1 second). CloudWatch keeps data for 15 months but rolls it up as it ages: 1-second points for 3 hours, 1-minute points for 15 days, 5-minute points for 63 days and 1-hour points for 455 days.
The hypervisor cannot see inside your instance, so memory use, disk space used and process counts are not default EC2 metrics. Install the CloudWatch agent, usually configured from an SSM Parameter Store parameter, to collect them along with log files. Metrics are grouped by namespace (like AWS/EC2) and dimensions (like InstanceId), and the same metric name with different dimensions is a different metric.
- Basic EC2 monitoring: 5 minutes. Detailed: 1 minute
- High-resolution custom metrics: down to 1 second
- Memory and disk space need the CloudWatch agent
- Retention: 15 months, with coarser points as data ages
Alarms that don't cry wolf
An alarm checks a statistic (Average, Sum, Maximum, or a percentile like p99) over a period, and goes to ALARM when M out of N recent data points breach the threshold. For example, 3 out of 5 one-minute periods above 80 percent ignores a single spike but still catches sustained trouble. States are OK, ALARM and INSUFFICIENT_DATA, and you choose how missing data counts: missing, notBreaching, breaching or ignore.
Alarm on symptoms users feel, such as error rate and p99 latency, rather than only on causes such as CPU. Composite alarms combine several alarms with AND or OR, which cuts noise: page someone only when errors are high and latency is high. Anomaly detection alarms learn a metric's normal daily shape and fire when it leaves that band, which works well for traffic that changes by hour.
- 1Data points
One per period, e.g. every 60 s
- 2Statistic
Average, Sum, Max or p99
- 3M of N check
e.g. 3 of the last 5 breach
- 4State change
OK to ALARM
- 5Actions
SNS, Auto Scaling, EC2 recover
CloudWatch Logs in practice
Logs are stored in log groups (one per app or function) made of log streams (one per instance or container). By default log groups never expire, which quietly grows your bill, so set a retention such as 30 or 90 days. Metric filters turn log patterns into metrics, for example counting lines containing ERROR, so you can alarm on them. Subscription filters stream log events in near real time to Lambda, Kinesis, Firehose or OpenSearch, which is how you centralise logs from many accounts.
Logs Insights queries look like this: fields @timestamp, @message | filter @message like /ERROR/ | stats count() by bin(5m). You pay per GB scanned, so narrow the time range. For long-term, cheap storage, export logs to S3 or deliver them there with Firehose. Lambda writes to CloudWatch Logs automatically; EC2 needs the agent.
CloudTrail: the audit record
Event history shows the last 90 days of management events (actions that create, change or delete resources, and many reads) in each Region for free, with no setup. For longer retention and analysis, create a trail that delivers log files to an S3 bucket, usually within about 5 minutes of the call, and optionally to CloudWatch Logs for alarms. An organization trail created in the management account records every account.
Data events are off by default because they are high volume and cost extra: S3 object reads and writes, Lambda invocations, DynamoDB item actions. Turn them on for sensitive buckets. CloudTrail Insights detects unusual API activity, such as a sudden burst of TerminateInstances calls. Log file integrity validation adds signed digest files, so you can prove logs were not altered. Protect the trail bucket with a strict bucket policy, ideally in a separate logging account.
- User to Amazon S3: DeleteBucket logs-old1DeleteBucket logs-old
- Amazon S3 to CloudTrail: Management event recorded2Management event recorded
- 3Delivered to trail bucket, about 5 minCloudTrail to CloudTrail: Delivered to trail bucket, about 5 min
- Security team to CloudTrail: lookup-events EventName=DeleteBucket4lookup-events EventName=DeleteBucket
- CloudTrail to Security team: userIdentity, sourceIPAddress, eventTime5userIdentity, sourceIPAddress, eventTime
AWS Config: drift and compliance
Once the configuration recorder is on, Config records a configuration item every time a supported resource changes, building a timeline: what this security group looked like last Tuesday, and which resources it was attached to. Config rules evaluate resources against a desired state, either when a resource changes or on a schedule. AWS provides hundreds of managed rules, such as encrypted-volumes, restricted-ssh and s3-bucket-public-read-prohibited, and you can write custom rules with Lambda or Guard.
Config detects; it does not block. To fix things automatically, attach a remediation action, an SSM Automation document that, for example, turns on bucket encryption. Conformance packs bundle rules for a standard, and an aggregator shows compliance across accounts and Regions. To prevent bad changes in the first place, use SCPs or IAM. Config is Regional and charges per configuration item recorded and per rule evaluation.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Create CloudWatch metrics and alarms~45m
- 2Centralise logs with CloudWatch Logs~45m
- 3Audit API calls with CloudTrail~45m
- 4Track compliance with AWS Config rules~45m
Key points
- EC2 memory and disk usage need the CloudWatch agent; they are not default metrics.
- Create an organization trail to log all accounts into one S3 bucket.
- Use Config rules to detect, for example, unencrypted EBS volumes.
- EventBridge can react to CloudTrail API events in near real time.
Key terms
Tap a card to flip it. 0/5 known
Examples
aws cloudwatch put-metric-alarm \
--alarm-name web-high-cpu \
--namespace AWS/EC2 --metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=i-0abc123 \
--statistic Average --period 300 \
--evaluation-periods 2 --threshold 80 \
--comparison-operator GreaterThanThreshold \
--alarm-actions arn:aws:sns:us-east-1:123456789012:opsAlarm when average CPU stays above 80 percent for 10 minutes.
Alarm on application errors found in logs
An app writes lines like level=ERROR to the log group /app/web, and the team wants a page when errors pass 10 per minute for 3 minutes. Step 1: create a metric filter that counts matching lines into a custom metric. Step 2: create an alarm on that metric with Sum over 60-second periods, 3 of 3 data points, treating missing data as not breaching because no errors means no data. Step 3: send the alarm to an SNS topic that pages the on-call engineer.
aws logs put-metric-filter --log-group-name /app/web --filter-name errors \
--filter-pattern '"level=ERROR"' \
--metric-transformations metricName=AppErrors,metricNamespace=MyApp,metricValue=1
aws cloudwatch put-metric-alarm --alarm-name web-errors-high \
--namespace MyApp --metric-name AppErrors --statistic Sum --period 60 \
--evaluation-periods 3 --datapoints-to-alarm 3 --threshold 10 \
--comparison-operator GreaterThanThreshold --treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:us-east-1:111122223333:oncallFind who opened SSH to the world
A Config rule flagged a security group with port 22 open to 0.0.0.0/0. Step 1: ask CloudTrail for recent AuthorizeSecurityGroupIngress calls to see who made the change, when and from which IP. Step 2: open the Config timeline for the security group to see the exact rule added and every resource attached to it. Step 3: remove the rule, then add automatic remediation to the Config rule so it is fixed within minutes next time.
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=AuthorizeSecurityGroupIngress \
--max-results 5 --query 'Events[].[EventTime,Username,CloudTrailEvent]'
aws configservice get-resource-config-history \
--resource-type AWS::EC2::SecurityGroup --resource-id sg-0abc1234 --limit 3Quick reference
- CloudWatch = performance now. CloudTrail = who called which API. Config = settings history and rules
- EC2 basic metrics every 5 min; detailed every 1 min; memory and disk need the agent
- Alarm states: OK, ALARM, INSUFFICIENT_DATA; use M of N data points to avoid noise
- Log groups never expire by default; set retention: aws logs put-retention-policy
- CloudTrail event history: 90 days of management events, free, per Region
- S3 object and Lambda invoke activity are data events: off by default, extra cost
- Config detects drift; remediate with SSM Automation; prevent with SCPs or IAM
- React to an API call in near real time: EventBridge rule on CloudTrail events
Common mistakes
- Using CloudTrail to monitor CPU, or CloudWatch to find who deleted a bucket.
- Expecting memory metrics from EC2 without installing the agent.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Set a 30-day retention on every log group in a Region that currently has none.
- Exercise 2medium
Write a Logs Insights query that shows the 10 slowest requests in the last hour from a JSON log with fields path and latency_ms, and the error count per 5 minutes.
- Exercise 3hard
Create a multi-Region trail with log file validation to a dedicated bucket, then add an EventBridge rule that notifies you whenever someone calls StopLogging.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between CloudWatch and CloudTrail?
- CloudWatch measures how resources and apps perform and holds their logs. CloudTrail records API calls, so it tells you who did something, not how fast the system is.
- Is CloudTrail on by default?
- Yes, event history keeps 90 days of management events for free in each Region. For longer storage, data events or delivery to S3, you create a trail.
- Does AWS Config stop non-compliant changes?
- No. Config detects and records them, and can trigger automatic remediation afterwards. To block changes up front, use SCPs, IAM policies or CloudFormation Guard checks in your pipeline.
- How long does CloudWatch keep metrics?
- Up to 15 months, but older data is stored at coarser resolution: 1-minute points for 15 days, 5-minute points for 63 days, and 1-hour points after that.