{"id":"cloudwatch","name":"cloudwatch","summary":"AWS CloudWatchによるログ、指標、アラーム、ダッシュボードの監視。モニタリングの設定、アラーム作成、Insightsによるログの照会、メトリクスフィルターの設定、ダッシュボード構築、アプリケーションのトラブルシューティングなどに活用してください。","body":"# AWS CloudWatch\n\nAmazon CloudWatch provides monitoring and observability for AWS resources and applications. It collects metrics, logs, and events, enabling you to monitor, troubleshoot, and optimize your AWS environment.\n\n## Table of Contents\n\n- [Core Concepts](#core-concepts)\n- [Common Patterns](#common-patterns)\n- [CLI Reference](#cli-reference)\n- [Best Practices](#best-practices)\n- [Troubleshooting](#troubleshooting)\n- [References](#references)\n\n## Core Concepts\n\n### Metrics\n\nTime-ordered data points published to CloudWatch. Key components:\n- **Namespace**: Container for metrics (e.g., `AWS/Lambda`)\n- **Metric name**: Name of the measurement (e.g., `Invocations`)\n- **Dimensions**: Name-value pairs for filtering (e.g., `FunctionName=MyFunc`)\n- **Statistics**: Aggregations (Sum, Average, Min, Max, SampleCount, pN)\n\n### Logs\n\nLog data from AWS services and applications:\n- **Log groups**: Collections of log streams\n- **Log streams**: Sequences of log events from same source\n- **Log events**: Individual log entries with timestamp and message\n\n### Alarms\n\nAutomated actions based on metric thresholds:\n- **States**: OK, ALARM, INSUFFICIENT_DATA\n- **Actions**: SNS notifications, Auto Scaling, EC2 actions\n\n## Common Patterns\n\n### Create a Metric Alarm\n\n**AWS CLI:**\n\n```bash\n# CPU utilization alarm for EC2\naws cloudwatch put-metric-alarm \\\n  --alarm-name \"HighCPU-i-1234567890abcdef0\" \\\n  --metric-name CPUUtilization \\\n  --namespace AWS/EC2 \\\n  --statistic Average \\\n  --period 300 \\\n  --threshold 80 \\\n  --comparison-operator GreaterThanThreshold \\\n  --evaluation-periods 2 \\\n  --dimensions Name=InstanceId,Value=i-1234567890abcdef0 \\\n  --alarm-actions arn:aws:sns:us-east-1:123456789012:alerts \\\n  --ok-actions arn:aws:sns:us-east-1:123456789012:alerts\n```\n\n**boto3:**\n\n```python\nimport boto3\n\ncloudwatch = boto3.client('cloudwatch')\n\ncloudwatch.put_metric_alarm(\n    AlarmName='HighCPU-i-1234567890abcdef0',\n    MetricName='CPUUtilization',\n    Namespace='AWS/EC2',\n    Statistic='Average',\n    Period=300,\n    Threshold=80.0,\n    ComparisonOperator='GreaterThanThreshold',\n    EvaluationPeriods=2,\n    Dimensions=[\n        {'Name': 'InstanceId', 'Value': 'i-1234567890abcdef0'}\n    ],\n    AlarmActions=['arn:aws:sns:us-east-1:123456789012:alerts'],\n    OKActions=['arn:aws:sns:us-east-1:123456789012:alerts']\n)\n```\n\n### Lambda Error Rate Alarm\n\n```bash\naws cloudwatch put-metric-alarm \\\n  --alarm-name \"LambdaErrorRate-MyFunction\" \\\n  --metrics '[\n    {\n      \"Id\": \"errors\",\n      \"MetricStat\": {\n        \"Metric\": {\n          \"Namespace\": \"AWS/Lambda\",\n          \"MetricName\": \"Errors\",\n          \"Dimensions\": [{\"Name\": \"FunctionName\", \"Value\": \"MyFunction\"}]\n        },\n        \"Period\": 60,\n        \"Stat\": \"Sum\"\n      },\n      \"ReturnData\": false\n    },\n    {\n      \"Id\": \"invocations\",\n      \"MetricStat\": {\n        \"Metric\": {\n          \"Namespace\": \"AWS/Lambda\",\n          \"MetricName\": \"Invocations\",\n          \"Dimensions\": [{\"Name\": \"FunctionName\", \"Value\": \"MyFunction\"}]\n        },\n        \"Period\": 60,\n        \"Stat\": \"Sum\"\n      },\n      \"ReturnData\": false\n    },\n    {\n      \"Id\": \"errorRate\",\n      \"Expression\": \"errors/invocations*100\",\n      \"Label\": \"Error Rate\",\n      \"ReturnData\": true\n    }\n  ]' \\\n  --threshold 5 \\\n  --comparison-operator GreaterThanThreshold \\\n  --evaluation-periods 3 \\\n  --alarm-actions arn:aws:sns:us-east-1:123456789012:alerts\n```\n\n### Query Logs with Insights\n\n```bash\n# Find errors in Lambda logs\naws logs start-query \\\n  --log-group-name /aws/lambda/MyFunction \\\n  --start-time $(date -d '1 hour ago' +%s) \\\n  --end-time $(date +%s) \\\n  --query-string '\n    fields @timestamp, @message\n    | filter @message like /ERROR/\n    | sort @timestamp desc\n    | limit 50\n  '\n\n# Get query results\naws logs get-query-results --query-id <query-id>\n```\n\n**boto3:**\n\n```python\nimport boto3\nimport time\n\nlogs = boto3.client('logs')\n\n# Start query\nresponse = logs.start_query(\n    logGroupName='/aws/lambda/MyFunction',\n    startTime=int(time.time()) - 3600,\n    endTime=int(time.time()),\n    queryString='''\n        fields @timestamp, @message\n        | filter @message like /ERROR/\n        | sort @timestamp desc\n        | limit 50\n    '''\n)\n\nquery_id = response['queryId']\n\n# Wait for results\nwhile True:\n    result = logs.get_query_results(queryId=query_id)\n    if result['status'] == 'Complete':\n        break\n    time.sleep(1)\n\nfor row in result['results']:\n    print(row)\n```\n\n### Create Metric Filter\n\nExtract metrics from log patterns:\n\n```bash\n# Create metric filter for error count\naws logs put-metric-filter \\\n  --log-group-name /aws/lambda/MyFunction \\\n  --filter-name ErrorCount \\\n  --filter-pattern \"ERROR\" \\\n  --metric-transformations \\\n    metricName=ErrorCount,metricNamespace=MyApp,metricValue=1,defaultValue=0\n```\n\n### Publish Custom Metrics\n\n```python\nimport boto3\n\ncloudwatch = boto3.client('cloudwatch')\n\ncloudwatch.put_metric_data(\n    Namespace='MyApp',\n    MetricData=[\n        {\n            'MetricName': 'OrdersProcessed',\n            'Value': 1,\n            'Unit': 'Count',\n            'Dimensions': [\n                {'Name': 'Environment', 'Value': 'Production'},\n                {'Name': 'OrderType', 'Value': 'Standard'}\n            ]\n        }\n    ]\n)\n```\n\n### Create Dashboard\n\n```bash\ncat > dashboard.json << 'EOF'\n{\n  \"widgets\": [\n    {\n      \"type\": \"metric\",\n      \"x\": 0, \"y\": 0, \"width\": 12, \"height\": 6,\n      \"properties\": {\n        \"title\": \"Lambda Invocations\",\n        \"metrics\": [\n          [\"AWS/Lambda\", \"Invocations\", \"FunctionName\", \"MyFunction\"]\n        ],\n        \"period\": 60,\n        \"stat\": \"Sum\",\n        \"region\": \"us-east-1\"\n      }\n    },\n    {\n      \"type\": \"log\",\n      \"x\": 12, \"y\": 0, \"width\": 12, \"height\": 6,\n      \"properties\": {\n        \"title\": \"Recent Errors\",\n        \"query\": \"SOURCE '/aws/lambda/MyFunction' | filter @message like /ERROR/ | limit 20\",\n        \"region\": \"us-east-1\"\n      }\n    }\n  ]\n}\nEOF\n\naws cloudwatch put-dashboard \\\n  --dashboard-name MyAppDashboard \\\n  --dashboard-body file://dashboard.json\n```\n\n## CLI Reference\n\n### Metrics Commands\n\n| Command | Description |\n|---------|-------------|\n| `aws cloudwatch put-metric-data` | Publish custom metrics |\n| `aws cloudwatch get-metric-data` | Retrieve metric values |\n| `aws cloudwatch get-metric-statistics` | Get aggregated statistics |\n| `aws cloudwatch list-metrics` | List available metrics |\n\n### Alarms Commands\n\n| Command | Description |\n|---------|-------------|\n| `aws cloudwatch put-metric-alarm` | Create or update alarm |\n| `aws cloudwatch describe-alarms` | List alarms |\n| `aws cloudwatch set-alarm-state` | Manually set alarm state |\n| `aws cloudwatch delete-alarms` | Delete alarms |\n\n### Logs Commands\n\n| Command | Description |\n|---------|-------------|\n| `aws logs create-log-group` | Create log group |\n| `aws logs put-log-events` | Write log events |\n| `aws logs filter-log-events` | Search log events |\n| `aws logs start-query` | Start Insights query |\n| `aws logs put-metric-filter` | Create metric filter |\n| `aws logs put-retention-policy` | Set log retention |\n\n## Best Practices\n\n### Metrics\n\n- **Use dimensions wisely** — too many creates metric explosion\n- **Aggregate before publishing** — batch custom metrics\n- **Use high-resolution metrics** (1-second) only when needed\n- **Set meaningful units** for custom metrics\n\n### Alarms\n\n- **Use composite alarms** for complex conditions\n- **Set appropriate evaluation periods** to avoid flapping\n- **Include OK actions** to track recovery\n- **Use anomaly detection** for dynamic thresholds\n\n### Logs\n\n- **Set retention policies** — don't keep logs forever\n- **Use structured logging** (JSON) for better querying\n- **Create metric filters** for key events\n- **Use Contributor Insights** for top-N analysis\n\n### Cost Optimization\n\n- **Delete unused dashboards**\n- **Reduce log retention** for non-critical logs\n- **Avoid high-resolution metrics** unless necessary\n- **Use log subscription filters** instead of polling\n\n## Troubleshooting\n\n### Missing Metrics\n\n**Causes:**\n- Service not publishing yet (wait 1-5 minutes)\n- Wrong namespace/dimensions\n- Detailed monitoring not enabled (EC2)\n\n**Debug:**\n\n```bash\n# List metrics for a namespace\naws cloudwatch list-metrics \\\n  --namespace AWS/Lambda \\\n  --dimensions Name=FunctionName,Value=MyFunction\n```\n\n### Alarm Stuck in INSUFFICIENT_DATA\n\n**Causes:**\n- Metric not being published\n- Dimensions mismatch\n- Evaluation period too short\n\n**Debug:**\n\n```bash\n# Check if metric has data\naws cloudwatch get-metric-statistics \\\n  --namespace AWS/Lambda \\\n  --metric-name Invocations \\\n  --dimensions Name=FunctionName,Value=MyFunction \\\n  --start-time $(date -d '1 hour ago' -u +%Y-%m-%dT%H:%M:%SZ) \\\n  --end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \\\n  --period 60 \\\n  --statistics Sum\n```\n\n### Log Events Not Appearing\n\n**Causes:**\n- IAM permissions missing\n- CloudWatch Logs agent not running\n- Log group doesn't exist\n\n**Debug:**\n\n```bash\n# Check log streams\naws logs describe-log-streams \\\n  --log-group-name /aws/lambda/MyFunction \\\n  --order-by LastEventTime \\\n  --descending \\\n  --limit 5\n```\n\n### High CloudWatch Costs\n\n**Check usage:**\n\n```bash\n# Get PutLogEvents usage\naws cloudwatch get-metric-statistics \\\n  --namespace AWS/Logs \\\n  --metric-name IncomingBytes \\\n  --dimensions Name=LogGroupName,Value=/aws/lambda/MyFunction \\\n  --start-time $(date -d '7 days ago' -u +%Y-%m-%dT%H:%M:%SZ) \\\n  --end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \\\n  --period 86400 \\\n  --statistics Sum\n```\n\n## References\n\n- [CloudWatch User Guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/)\n- [CloudWatch Logs User Guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/)\n- [CloudWatch API Reference](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/)\n- [CloudWatch CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/cloudwatch/)\n- [Logs Insights Query Syntax](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html)\n- [boto3 CloudWatch](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudwatch.html)","author":"@itsmostafa","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/cloudwatch","license":"MIT","category":null,"lang":"en","tokens":2662,"stars":0,"calls30d":1,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"alarms-metrics.md","size":11278,"sha256":"e79fc78d2453ddc441bd9b33f3f38923831979141cb3556ad070a110dded406e"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["boto3.amazonaws.com","docs.aws.amazon.com"]}}