# Monitoring and auditing: CloudWatch, CloudTrail and Config

Read metrics, search logs, set alarms that fire before users notice, and keep an audit trail of every change.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 13. About 25 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/13-cloudwatch

## What you will learn

- Read a metric by namespace, name and dimensions
- Create a log group with retention and search it with Logs Insights
- Create an alarm and dashboard that answer an operational question
- Explain what CloudTrail records and what AWS Config evaluates
- Clean up monitoring resources so a practice account does not accumulate cost

## Metrics have context

Before shared monitoring, a team often learned about an outage from a customer and searched server by server.
That is slow because the first symptom rarely points to the failing component. CloudWatch gives the team shared
signals: metrics show whether a value changed, logs show what a component recorded, and alarms turn a defined
condition into action.

When a user says “the service is slow”, I need a signal that narrows the search. CloudWatch metrics are numbers
with context. A metric has a namespace, a name, a unit and zero or more dimensions.

The namespace keeps unrelated numbers apart. The name says what is measured. A dimension identifies the thing being
measured, such as an instance ID or environment. The same metric name with a different dimension is a different time
series.

EC2 publishes metrics such as `CPUUtilization` for instances. You can also publish an application metric:

```sh
$ aws cloudwatch put-metric-data \
    --namespace DevOpsAcademy/Demo \
    --metric-data 'MetricName=QueueDepth,Dimensions=[{Name=Environment,Value=practice}],Value=3,Unit=Count'
```

I used this command in `ap-south-1`. It returned no text, which is a successful `PutMetricData` response. Find it
under CloudWatch → Metrics → All metrics → `DevOpsAcademy/Demo`.

A custom metric is emitted by your code or an agent. Give it a useful name and stable dimensions. If a process
invents a new dimension value for every request, the number of time series grows quickly.

Use dimensions to split a metric only when you expect to compare those groups, such as environment or instance.
The namespace keeps your application metric apart from AWS service metrics. The unit helps a graph or alarm
interpret the value, and the timestamp places it in a period. Together, these fields answer what was measured,
where it came from and when it happened. Pick names that stay stable across deploys. A renamed dimension can make
a healthy service look like it stopped publishing the old time series.

## Logs are a stream

Metrics tell me that something changed. Logs help me explain why. A log event has a timestamp and a message. A
log group is the container for streams from one application or class of resource. Set retention deliberately; the
default is Never Expire.

A log stream is a sequence of events from one source, such as a function instance or a server. Groups give you a
place to set retention and access boundaries across related streams. The event timestamp lets you sort by time;
the message holds what the application recorded. Logs complement metrics: a metric can reveal that errors rose,
while matching log events may show the exception or request path. Use structured fields where possible so queries
can filter reliably. Before increasing retention, ask how long the data is useful and who should read it.

```sh
$ aws logs create-log-group --log-group-name /academy/cloudwatch-demo
$ aws logs put-retention-policy \
    --log-group-name /academy/cloudwatch-demo \
    --retention-in-days 7
```

CloudWatch Logs Insights reads selected groups. This query finds recent events:

```text
fields @timestamp, @message
| sort @timestamp desc
| limit 20
```

> **Retention is a data decision.** Logs can contain tokens, request bodies or customer data. Do not log secrets. Choose retention with your security and incident-response needs in mind, then restrict who may read the group. Deleting a log group removes its events.

> **Video.** [🚀 AWS CloudWatch for Absolute Beginners (2026) | Logs, Metrics, Alarms & Dashboards](https://www.youtube.com/watch?v=L8qt9Pse0-U&t=184s) (AWS with Jaymit)

## Alarms turn data into action

An alarm is a rule over a metric. It needs a statistic, period, threshold and number of evaluation periods. It can
be `OK`, `ALARM` or `INSUFFICIENT_DATA`. Missing data is a decision too.

CloudWatch groups samples into each period, calculates the chosen statistic, then compares it with the threshold.
The evaluation periods determine how many periods must meet the condition before the alarm changes state. More
periods can reduce noise from a brief spike, but can delay a real alert. `INSUFFICIENT_DATA` means CloudWatch
cannot evaluate enough points; it is not the same as healthy. Decide how to treat missing points based on how the
metric is emitted. Attach an action only when a person or automation can respond, and link that action to a clear
next step in the runbook.

```sh
$ aws cloudwatch put-metric-alarm \
    --alarm-name academy-cloudwatch-demo-alarm \
    --namespace DevOpsAcademy/Demo \
    --metric-name QueueDepth \
    --dimensions Name=Environment,Value=practice \
    --statistic Average \
    --period 60 \
    --evaluation-periods 1 \
    --threshold 10 \
    --comparison-operator GreaterThanOrEqualToThreshold \
    --treat-missing-data notBreaching
```

For production, choose a threshold from a service objective. Add an SNS action when a human or automation must be
notified. Lesson 14 uses SNS and SQS in detail.

> **Video.** [AWS Cloudwatch Alarm Setup Tutorial | Step by Step](https://www.youtube.com/watch?v=lHWrAAzoxJA) (Be A Better Dev)

> **Figure.** Metrics such as an EC2 instance's CPUUtilization arrive every minute, and logs can become metrics through a metric filter that counts lines such as ERROR. An alarm, academy-cloudwatch-demo-alarm, watches a metric against a threshold, for example CPU above 70 percent for 3 of 3 periods of 1 minute, and moves between the states OK, ALARM and INSUFFICIENT_DATA. When it enters ALARM it runs actions: notify an SNS topic that emails the team, or scale an Auto Scaling group. A dashboard shows the same metrics for people.
>
> Metrics and logs feed an alarm; when its state changes it notifies people or fixes the problem.

## A dashboard answers one question

A dashboard is a shared view, not a monitoring strategy. Put the few signals that answer one operational question
on it. This widget shows one practice metric:

```sh
$ aws cloudwatch put-dashboard \
    --dashboard-name academy-cloudwatch-demo-dashboard \
    --dashboard-body '{"widgets":[{"type":"metric","x":0,"y":0,"width":12,"height":6,"properties":{"view":"timeSeries","title":"Practice queue depth","region":"ap-south-1","metrics":[["DevOpsAcademy/Demo","QueueDepth","Environment","practice"]],"period":60,"stat":"Average"}}]}'
```

The real command returned a validation response with an empty `DashboardValidationMessages` array. The widget is
small: one graph, one question and no decorative noise.

The dashboard helps when its widgets answer one operational question, such as whether a queue is growing and a
worker is keeping up. A metric widget selects a namespace, metric, dimensions, statistic and time range. The same
metric can also feed an alarm, so the responder can inspect the trend behind its state. Keep the view focused: a
wall of unrelated graphs makes changes harder to spot. Dashboards do not collect signals by themselves. Confirm
that the service publishes the metrics you need before relying on the view.

> **Video.** [How To Create a CloudWatch Dashboard | Step by Step Walkthrough](https://www.youtube.com/watch?v=5QK3FB1EsV0) (Be A Better Dev)

## Events are different from metrics

EventBridge carries discrete events, such as “an EC2 instance changed state”. A metric is a measurement over time.
Use an EventBridge rule when the fact of the event should trigger a target; use an alarm when a measurement crossing
a threshold should trigger action.

“An instance entered the stopped state” is one event at one moment. “CPU stayed above 80 percent for five
minutes” is a metric condition over time. EventBridge rules match fields in an event and route matches to a target.
Alarms evaluate a time series and change state when a condition holds. Choose the event path for discrete facts
and the alarm path for sustained measurements. If an event should start work, choose a target that can handle
retries and failures. If an alarm should page someone, make the action and owner clear.

> **Video.** [Amazon CloudWatch and EventBridge](https://www.youtube.com/watch?v=gCyOPHlp5Ic) (Digital Cloud Training)

## Audit the API

CloudTrail answers who called which AWS API, when, from which source and with what result. CloudTrail Event history
gives a recent view. A production trail sends events to an S3 bucket and often to a log group with controls around
retention and access.

An EC2 launch, a security-group change and the deletion of this lesson’s alarm become API events. CloudTrail records
the AWS control plane, not every request handled by your application.

This answers a different incident question from a metric: who changed the resource before the outage? Event
history is useful for recent console investigations. A trail gives you a longer-lived record that you can route
to storage and protect with explicit access and retention. CloudTrail records AWS API activity; it does not
replace application logs or capture every SQL query sent over a database connection. Use both when an
investigation needs to connect an infrastructure change with what the application observed.

> **Video.** [AWS CloudTrail – API Auditing, Events, and Monitoring](https://www.youtube.com/watch?v=IIgMX2ILK6g) (Digital Cloud Training)

## Audit the configuration

AWS Config evaluates resource configuration against rules. CloudTrail can tell you that a security group changed;
Config can tell you whether the resulting group violates a rule. This gives you both a timeline and current
compliance state.

Config rules and recorders cost money in some configurations. I did not enable a recorder for this lesson because it
was outside the approved practice resources. Enable it deliberately in a real account and verify cost first.

Config keeps a history of supported resource settings and evaluates them against rules. A rule can answer whether
a resource currently meets a requirement, such as whether a bucket blocks public access. When a setting changes,
Config can record the new state and its compliance result. That complements CloudTrail: CloudTrail is the
actor-and-action timeline, while Config describes resource state and compliance. Recording and rules must be
configured first, and they can add cost. Start with the resource types and checks the team needs rather than
recording everything without an owner.

> **In production.** Start with a service-level question, then choose the signal: metric for a number, log for detail, alarm for a threshold, EventBridge for a discrete event, CloudTrail for API history and Config for resource compliance.

> **Video.** [AWS re:Invent 2020: Achieve compliance as code using AWS Config](https://www.youtube.com/watch?v=m8vTwvbzOfw) (AWS Events)

## Custom metrics and dimensions

Namespaces keep application metrics separate from AWS service metrics. Dimensions identify a time series, so keep
their values bounded: `Environment=practice` is useful; a request ID dimension creates an uncontrolled number of
series. Emit a metric from code or the CloudWatch agent when the managed service metric is not enough.

> **Figure.** CloudWatch metrics console showing a custom application metric
>
> The custom namespace is selected. The metric and bounded environment dimension identify the series.

> **Video.** [AWS CloudWatch Custom Metrics Lightning Tutorial](https://www.youtube.com/watch?v=40LmU4vsSSg&t=22s) (Code to the Moon)

## Logs Insights and metric filters

Logs Insights searches selected log groups with a query language. Start with `fields @timestamp, @message`, sort by
time, and limit the result while investigating. A metric filter turns matching log text such as `ERROR` into a
metric. Filters are useful for simple counters; use structured application metrics when the event needs richer labels.

> **Figure.** CloudWatch Logs console showing the practice log group and retention settings
>
> The practice log group is the search boundary. Retention is explicit instead of Never Expire.

> **Video.** [CloudWatch Logs Insights Tutorial: Query and Analyze AWS Logs Like a Pro](https://www.youtube.com/watch?v=HE7pNygqxKY) (CodeLucky)

## Static, composite and anomaly alarms

A static alarm is easy to explain: a statistic crosses a threshold for a number of periods. A composite alarm combines
child states so an operator receives one decision instead of several related pages. Anomaly detection learns a normal
band and alerts when the signal leaves it; it is useful for seasonal or changing workloads, not for a hard safety limit.
Alarm actions can publish to SNS, invoke automation or scale a resource. Treat an alarm as a runbook entry, not just a
red icon.

> **Figure.** CloudWatch alarm page showing a QueueDepth alarm and a composite alarm in the alarm list
>
> The static alarm is in ALARM because the custom value is above five. A sibling alarm is OK. The composite alarm is visible as a single operational view.

## Dashboards and the CloudWatch agent

A dashboard should answer one question for one audience. Do not turn it into a wall of every metric. The CloudWatch
agent adds host memory and disk signals that basic EC2 metrics do not publish. Configure it with least-privilege
permissions and a short retention policy for practice data. Container Insights adds task and container dimensions;
enable it only when the additional cost and signal volume are justified.

> **Figure.** CloudWatch dashboard with a custom queue-depth widget
>
> The dashboard has one question-oriented widget. The time series is the same custom metric used by the alarm.

## Traces, events and configuration evidence

X-Ray traces and Application Signals connect latency across service boundaries; use them when metrics show a symptom
but not the slow dependency. EventBridge rules route matching events to targets. CloudTrail records API activity, while
AWS Config evaluates resource configuration against rules. They answer different questions: what happened, what event
should trigger work, and whether the current resource state meets policy.

A trace follows one request across instrumented services. Its segments show where time was spent, helping you
distinguish a slow API from a slow database call. Start with metrics to notice a service-level symptom, then use
a trace to follow a representative request across boundaries. Use EventBridge when a discrete event should start
work, CloudTrail when you need AWS API history, and Config when you need the current compliance state. These
tools complement one another; enabling all of them without an operational question creates data and cost without
a useful decision.

## Mission: Make a small monitoring stack

Publish one custom metric, create one seven-day log group, one alarm and one dashboard, then prove their state with describe commands. Delete every practice resource and verify that the queries return empty results.

- You need: An AWS account, the AWS CLI configured with the anythinkx profile, and ap-south-1
- You'll have: A metric, a log group, an OK alarm and a dashboard, followed by empty cleanup queries

```sh
$ REGION=ap-south-1
$ PROFILE=anythinkx
$ LOG_GROUP=/academy/cloudwatch-demo
$ ALARM=academy-cloudwatch-demo-alarm
$ DASHBOARD=academy-cloudwatch-demo-dashboard
$ aws cloudwatch put-metric-data --profile $PROFILE --region $REGION --namespace DevOpsAcademy/Demo --metric-data 'MetricName=QueueDepth,Dimensions=[{Name=Environment,Value=practice}],Value=3,Unit=Count'
$ aws logs create-log-group --profile $PROFILE --region $REGION --log-group-name $LOG_GROUP
$ aws logs put-retention-policy --profile $PROFILE --region $REGION --log-group-name $LOG_GROUP --retention-in-days 7
$ aws cloudwatch put-metric-alarm --profile $PROFILE --region $REGION --alarm-name $ALARM --namespace DevOpsAcademy/Demo --metric-name QueueDepth --dimensions Name=Environment,Value=practice --statistic Average --period 60 --evaluation-periods 1 --threshold 10 --comparison-operator GreaterThanOrEqualToThreshold --treat-missing-data notBreaching
$ aws cloudwatch put-dashboard --profile $PROFILE --region $REGION --dashboard-name $DASHBOARD --dashboard-body '{"widgets":[{"type":"metric","x":0,"y":0,"width":12,"height":6,"properties":{"view":"timeSeries","title":"Practice queue depth","region":"ap-south-1","metrics":[["DevOpsAcademy/Demo","QueueDepth","Environment","practice"]],"period":60,"stat":"Average"}}]}'
$ aws logs describe-log-groups --profile $PROFILE --region $REGION --log-group-name-prefix $LOG_GROUP --query 'logGroups[].logGroupName'
$ aws cloudwatch describe-alarms --profile $PROFILE --region $REGION --alarm-names $ALARM --query 'MetricAlarms[].StateValue'
$ aws cloudwatch delete-alarms --profile $PROFILE --region $REGION --alarm-names $ALARM
$ aws cloudwatch delete-dashboards --profile $PROFILE --region $REGION --dashboard-names $DASHBOARD
$ aws logs delete-log-group --profile $PROFILE --region $REGION --log-group-name $LOG_GROUP
$ aws logs describe-log-groups --profile $PROFILE --region $REGION --log-group-name-prefix $LOG_GROUP --query 'logGroups[].logGroupName'
$ aws cloudwatch describe-alarms --profile $PROFILE --region $REGION --alarm-names $ALARM --query 'MetricAlarms[].AlarmName'
```

If you launch an instance for CPU metrics, terminate it first, wait for `terminated`, then delete any resources you
created for it. Never leave a running instance while you move to the next lesson.

## Try it

- Open CloudWatch Metrics and find an EC2 CPUUtilization metric by instance ID.
- Run the custom metric command and find QueueDepth under DevOpsAcademy/Demo.
- Open the alarm and read its period, threshold, statistic and missing-data treatment.
- Open CloudWatch Logs Insights and run a fields-and-sort query.
- Open CloudTrail Event history and filter Event source to ec2.amazonaws.com.
- Create a short-lived dashboard, inspect it, then delete it and confirm it is gone.

## Quiz

1. What identifies one CloudWatch metric stream?
   - Its dashboard name only
   - **Its namespace, metric name and dimensions** (answer)
   - The IAM user that created it
   Why: A namespace groups related metrics, the name says what is measured, and dimensions distinguish resource or workload variants.

2. An alarm has a 60-second period and one evaluation period. What does it evaluate?
   - **One minute of data before deciding whether the threshold is breached** (answer)
   - Every request made by the account since it was created
   - Only the last dashboard refresh
   Why: The period is the aggregation window. One evaluation period means one such window is enough to change state.

3. Why set log-group retention instead of accepting Never Expire?
   - Retention changes the log format
   - **It limits how long old events remain and controls storage cost and data exposure** (answer)
   - It makes Logs Insights free
   Why: CloudWatch Logs keeps events indefinitely by default. Retention is an operational and security decision.

4. What is CloudTrail mainly for?
   - **Recording API activity such as who changed an EC2 security group** (answer)
   - Replacing application logs
   - Measuring CPU every second
   Why: CloudTrail answers who called which AWS API, when, from where and whether it succeeded.

5. What should you do with a practice dashboard, alarm and log group after the exercise?
   - Leave them because empty resources never matter
   - **Delete them and verify the delete calls, while keeping any required account-wide trail intact** (answer)
   - Delete the account root user
   Why: Cleanup prevents forgotten resources and keeps the practice account predictable.

6. What does a composite alarm add?
   - **It combines alarm states into one operational decision** (answer)
   - It stores log events
   - It replaces CloudTrail
   Why: Composite alarms reduce alert noise by expressing relationships between child alarms.

7. When is anomaly detection useful?
   - **When a metric has a learned normal range instead of one fixed threshold** (answer)
   - When a log group needs a name
   - When an API call needs an IAM role
   Why: Anomaly detection models expected behavior and can flag deviations that a static threshold misses.

## Resources

- [CloudWatch user guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) (AWS Docs)
- [CloudWatch metrics concepts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html) (AWS Docs)
- [CloudWatch Logs Insights query syntax](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html) (AWS Docs)
- [AWS CloudTrail user guide](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) (AWS Docs)
- [AWS Config developer guide](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html) (AWS Docs)
