Không có CloudWatch, bạn mù hoàn toàn khi app có vấn đề. CloudWatch là mắt và tai của app trên AWS, nhưng nhiều team chỉ dùng nó để xem log. Nó làm 4 việc: log (application logs), metric (CPU, latency, errors), alarm (cảnh báo), dashboard (trực quan hóa).


  flowchart LR
    App["Lambda/ECS/EC2"] --> Logs["CloudWatch Logs"]
    Logs --> Metric["Metric Filter → Custom Metric"]
    Metric --> Alarm["CloudWatch Alarm<br/>→ SNS → Slack/PagerDuty"]
    Metric --> Dashboard["Dashboard<br/>single pane of glass"]
```text

## Log Group và Retention

### Log Group Retention

```bash
aws logs put-retention-policy --log-group-name /aws/lambda/api-handler --retention-in-days 30
```text

**Luôn set retention.** Default = infinite → cost tăng mãi mãi. Standard: 30 ngày cho app log, 90 ngày cho audit log.

### Logs Insights Queries

## Logs Insights

```text
fields @timestamp, @message
| filter @message like /ERROR/
| stats count() by bin(5m)
| sort @timestamp desc

filter @type = "REPORT"
| stats pct(@duration, 50) as p50, pct(@duration, 95) as p95, pct(@duration, 99) as p99
```text

### EMF: Custom Metric Không Cần API Call

## EMF — Custom Metric không cần API call

```typescript
console.log(JSON.stringify({
  _aws: {
    Timestamp: Date.now(),
    CloudWatchMetrics: [{ Namespace: "MyApp", Dimensions: [["status"]], Metrics: [{ Name: "Requests", Unit: "Count" }] }],
  },
  status: "success", Requests: 1,
}));
```text

### Composite Alarm

## Composite Alarm

```bash
aws cloudwatch put-composite-alarm --alarm-name api-critical \
  --alarm-rule 'ALARM("api-5xx-high") AND ALARM("api-latency-p95-high")' \
  --alarm-actions $SNS_ARN
```text

4 thứ này — log, metric, alarm, dashboard — là tối thiểu để không mù khi deploy. Bài sau sẽ nói về EMF và anomaly detection để chủ động hơn nữa.

Bài sau: [Phần 33: CloudWatch nâng cao — EMF, Insights, anomaly detection](/posts/aws/33-cloudwatch-nang-cao-emf-insights-anomaly/)