Amazon CloudWatch
Metrics, Alarms, Logs, Dashboards, Insights
Tổng Quan
Amazon CloudWatch là dịch vụ monitoring và observability toàn diện của AWS, cho phép bạn giám sát tài nguyên AWS, ứng dụng và dịch vụ chạy trên cloud hoặc on-premises.
CloudWatch Core Components
| Component | Mô Tả | Use Case |
|---|---|---|
| Metrics | Dữ liệu time-series về performance | CPU, Memory, Network I/O |
| Logs | Thu thập và lưu trữ log files | Application logs, System logs |
| Alarms | Cảnh báo dựa trên metrics | Notify khi CPU > 80% |
| Dashboards | Visualization tập trung | Tổng hợp metrics nhiều services |
| Events | React to AWS resource changes | Trigger Lambda khi EC2 stop |
| Insights | Query và analyze logs | Troubleshooting, Analytics |
| Synthetics | Canary scripts | Monitor endpoints, APIs |
| ServiceLens | End-to-end observability | Distributed tracing |
CloudWatch Metrics
1. Metrics Là Gì?
Metric là một biến đo lường theo thời gian (time-series data), ví dụ: CPU utilization của EC2 instance.
2. Metrics Structure
| Component | Mô Tả | Ví Dụ |
|---|---|---|
| Namespace | Container cho metrics | AWS/EC2, AWS/RDS, Custom/MyApp |
| Metric Name | Tên của metric | CPUUtilization, RequestCount |
| Dimensions | Key-value pairs để filter | InstanceId, AutoScalingGroupName |
| Timestamp | Thời điểm data point | ISO 8601 format |
| Value | Giá trị đo được | 45.5, 1024 |
| Unit | Đơn vị đo | Percent, Bytes, Count |
3. Default Metrics vs Detailed Monitoring
| Loại | Resolution | Chi Phí | Availability |
|---|---|---|---|
| Basic (Default) | 5 phút | Miễn phí | Tất cả EC2 instances |
| Detailed Monitoring | 1 phút | Có phí | Phải enable |
| High-Resolution Custom | 1 giây | Có phí cao hơn | Custom metrics only |
4. Important Default Metrics by Service
EC2 Instance Metrics
| Metric | Mô Tả | ⚠️ Lưu Ý |
|---|---|---|
CPUUtilization | % CPU được sử dụng | Default có sẵn |
NetworkIn/Out | Bytes network traffic | Default có sẵn |
DiskReadBytes/WriteBytes | Disk I/O bytes | Instance store only |
StatusCheckFailed | Health check status | System & Instance check |
MemoryUtilization | % RAM sử dụng | ❌ KHÔNG CÓ mặc định - Cần CloudWatch Agent |
DiskSpaceUtilization | % Disk sử dụng | ❌ KHÔNG CÓ mặc định - Cần CloudWatch Agent |
[!IMPORTANT] Memory và Disk Space KHÔNG được thu thập mặc định bởi CloudWatch. Bạn cần cài đặt CloudWatch Agent để có các metrics này.
RDS Metrics
| Metric | Mô Tả |
|---|---|
CPUUtilization | CPU % |
DatabaseConnections | Số connections đang mở |
FreeableMemory | RAM khả dụng |
ReadIOPS/WriteIOPS | I/O operations per second |
FreeStorageSpace | Disk space còn lại |
Lambda Metrics
| Metric | Mô Tả |
|---|---|
Invocations | Số lần function được gọi |
Duration | Thời gian thực thi (ms) |
Errors | Số lần lỗi |
Throttles | Số lần bị throttle |
ConcurrentExecutions | Số executions đồng thời |
5. Custom Metrics
Bạn có thể push custom metrics từ ứng dụng của mình:
6. Namespace và Dimensions Chi Tiết
Namespace là gì?
Namespace là container/category để nhóm các metrics liên quan lại với nhau. Nó giống như một "thư mục" để tổ chức metrics.
| AWS Service | Namespace |
|---|---|
| EC2 | AWS/EC2 |
| RDS | AWS/RDS |
| Lambda | AWS/Lambda |
| ALB | AWS/ApplicationELB |
| DynamoDB | AWS/DynamoDB |
| S3 | AWS/S3 |
| SQS | AWS/SQS |
| Custom | MyCompany/MyApp (tự đặt, KHÔNG dùng AWS/ prefix) |
Dimensions là gì?
Dimensions là key-value pairs dùng để xác định và phân loại một metric cụ thể. Nó giống như "filters/tags" để phân biệt các metrics cùng tên.
| Service | Common Dimensions |
|---|---|
| EC2 | InstanceId, AutoScalingGroupName, ImageId |
| RDS | DBInstanceIdentifier, DBClusterIdentifier |
| Lambda | FunctionName, Resource, Version |
| ALB | LoadBalancer, TargetGroup, AvailabilityZone |
| SQS | QueueName |
| DynamoDB | TableName, GlobalSecondaryIndexName |
Tổng hợp: Namespace + MetricName + Dimensions
CloudWatch Logs
1. Logs Architecture
| Concept | Mô Tả | Ví Dụ |
|---|---|---|
| Log Group | Container cho related log streams | /aws/lambda/my-function |
| Log Stream | Sequence of events từ cùng source | 2024/01/15/[$LATEST]abc123 |
| Log Event | Single log entry với timestamp | {"timestamp": ..., "message": "..."} |
2. Log Sources
Có 2 nhóm nguồn chính gửi logs đến CloudWatch:
| Nhóm | Cách Gửi Logs | Ví Dụ |
|---|---|---|
| AWS Native | Tự động hoặc enable trong console | Lambda logs tự động đến /aws/lambda/<function-name> |
| Custom Sources | Cài CloudWatch Agent hoặc dùng SDK | EC2 cần install agent để push /var/log/* |
3. Log Retention
[!WARNING] Mặc định logs KHÔNG bao giờ expire! Điều này có thể gây ra chi phí lưu trữ cao. Luôn set retention policy phù hợp.
4. Log Export & Integration
| Export Method | Use Case | Real-time? |
|---|---|---|
| S3 Export | Archival, long-term storage, Athena analysis | ❌ Batch (up to 12h delay) |
| Subscription Filter → Kinesis Firehose | Real-time streaming to S3/OpenSearch | ✅ Near real-time |
| Subscription Filter → Lambda | Custom processing, alerting | ✅ Near real-time |
| Subscription Filter → Kinesis Data Streams | Complex event processing | ✅ Real-time |
5. CloudWatch Logs Insights
Query language mạnh mẽ để analyze logs:
🔔 CloudWatch Alarms
1. Alarm States
| State | Ý Nghĩa |
|---|---|
| OK | Metric trong ngưỡng bình thường |
| ALARM | Metric đã vượt ngưỡng |
| INSUFFICIENT_DATA | Không đủ data để đánh giá (mới tạo hoặc metric không có data) |
2. Alarm Configuration
3. Alarm Actions
| Action Type | Use Case | Example |
|---|---|---|
| SNS | Notifications | Email, SMS, Lambda trigger |
| Auto Scaling | Scale resources | Add EC2 when CPU > 80% |
| EC2 Stop | Cost optimization | Stop dev instance after hours |
| EC2 Terminate | Cleanup | Terminate unhealthy instance |
| EC2 Recover | Self-healing | Recover failed instance |
| Systems Manager | Automation | Run remediation runbook |
4. Composite Alarms
Combine multiple alarms với AND/OR logic:
🖥️ CloudWatch Agent
1. Tại Sao Cần CloudWatch Agent?
2. Agent Installation & Configuration
3. Agent Configuration File
CloudWatch Dashboards
1. Dashboard Features
2. Widget Types
| Widget Type | Use Case | Example |
|---|---|---|
| Line | Time series trends | CPU over time |
| Stacked Area | Show composition | Memory breakdown |
| Number | Single current value | Error count |
| Gauge | Show vs threshold | CPU vs 80% limit |
| Bar | Compare values | Requests by endpoint |
| Pie | Show distribution | Traffic by region |
| Text | Markdown content | Instructions, links |
| Alarm Status | Show alarm states | Critical alarms |
| Logs Table | Recent log entries | Error logs |
| Explorer | Dynamic resource view | All EC2 instances |
3. Cross-Account & Cross-Region Dashboards
CloudWatch Synthetics (Canaries)
1. Canary Overview
Canaries là configurable scripts chạy theo schedule để monitor endpoints và APIs.
2. Canary Use Cases
| Use Case | Description |
|---|---|
| Heartbeat Monitoring | Simple availability check |
| API Monitoring | Validate API responses |
| UI Workflow | Test login flows, checkout process |
| Visual Monitoring | Screenshot comparison |
| Broken Link Checker | Find 404 errors |
3. Sample Canary Script (Node.js)
CloudWatch ServiceLens & X-Ray Integration
1. End-to-End Observability
2. ServiceLens Features
| Feature | Description |
|---|---|
| Service Map | Visual map of application dependencies |
| Trace Analysis | Follow requests across services |
| Correlated Metrics | Link traces with CloudWatch metrics |
| Latency Analysis | Identify slow components |
| Error Tracking | Trace error paths |
CloudWatch Container Insights
1. Container Monitoring
2. Container Insights Metrics
| Level | Metrics Collected |
|---|---|
| Cluster | Node count, Pod count, CPU/Memory reservation |
| Node | CPU, Memory, Network, Filesystem, Pod count |
| Pod | CPU, Memory, Network, Container restarts |
| Container | CPU, Memory limits/requests |
EventBridge Integration (formerly CloudWatch Events)
[!NOTE] CloudWatch Events đã được rebrand thành Amazon EventBridge. Xem file
eventbridge.mdđể biết chi tiết đầy đủ.
CloudWatch Pricing
1. Pricing Components
| Component | Free Tier | Paid Pricing |
|---|---|---|
| Metrics | 10 custom metrics | $0.30/metric/month (first 10K) |
| Dashboards | 3 dashboards | $3/dashboard/month |
| Alarms | 10 alarms | $0.10/alarm/month (standard) |
| Logs Ingestion | 5GB | $0.50/GB |
| Logs Storage | 5GB | $0.03/GB/month |
| Logs Insights | None | $0.005/GB scanned |
| Contributor Insights | 1 rule | $0.02/matching log event |
| Canaries | None | $0.0012/canary run |
2. Cost Optimization Tips
Common Use Cases & Best Practices
1. Basic EC2 Monitoring Setup
2. Application Logging Pattern
3. Metric Filter for Error Counting
CloudWatch FAQ
Q: CloudWatch Agent vs Built-in Metrics - Khi nào cần Agent?
| Scenario | Cần Agent? |
|---|---|
| Monitor CPU/Network của EC2 | ❌ Không |
| Monitor Memory của EC2 | ✅ Có |
| Monitor Disk Space | ✅ Có |
| Collect application logs từ EC2 | ✅ Có |
| Monitor Lambda metrics | ❌ Không (tự động) |
| Monitor on-premises servers | ✅ Có |
Q: Log Group vs Log Stream?
Q: Standard vs High-Resolution Metrics?
| Aspect | Standard | High-Resolution |
|---|---|---|
| Resolution | 1 minute | 1 second |
| Retention | 15 months | 3 hours (then aggregated) |
| Cost | Lower | ~10x higher |
| Use Case | Most workloads | Real-time trading, gaming |
Q: CloudWatch Alarms vs EventBridge?
| Feature | CloudWatch Alarms | EventBridge |
|---|---|---|
| Trigger Based On | Metric thresholds | Events/State changes |
| Example | CPU > 80% for 5 min | EC2 instance stopped |
| Actions | SNS, EC2, Auto Scaling | Lambda, Step Functions, SQS, etc. |
| Pattern Matching | Simple threshold | Complex event patterns |
Related Services
| Service | Relationship với CloudWatch |
|---|---|
| SNS | Nhận alarm notifications |
| EventBridge | Event-driven automation (successor of CW Events) |
| X-Ray | Distributed tracing, ServiceLens integration |
| Auto Scaling | Scale based on CW metrics/alarms |
| Systems Manager | Run automation based on alarms |
| Lambda | Log destination, alarm target |
| Kinesis Firehose | Real-time log streaming |