---
# System prepended metadata

title: EC2 add log to cloudwatch

---

# EC2 add log to cloudwatch

1.install cloudwatch agent

```powershell
msiexec /i https://s3.amazonaws.com/amazoncloudwatch-agent/windows/amd64/latest/amazon-cloudwatch-agent.msi
```

default path:C:\Program Files\Amazon\AmazonCloudWatchAgent

![](https://hackmd.io/_uploads/BJ69-2g6h.png)


2. add IAM role to EC2 for cloudwatch agent

add role name:CloudWatchAgentServerRole with policy “CloudWatchAgentServerPolicy“

![](https://hackmd.io/_uploads/Syynbhgph.png)


3. System Manager新增 agent config

![](https://hackmd.io/_uploads/ByB6Z3e63.png)


```json
{
   "logs":{
      "logs_collected":{
         "files":{
            "collect_list":[
               {
                  "file_path":"C:\\Logs\\**.log",
                  "log_group_name":"EC2/MyApplication",
                  "log_stream_name":"{instance_id}",
                  "timestamp_format":"%Y-%m-%d %H:%M:%S,%f",
            "multi_line_start_pattern": "{timestamp_format}"
               }
            ]
         },
         "windows_events":{
            "collect_list":[
               {
                  "event_format":"xml",
                  "event_levels":[
                     "WARNING",
                     "ERROR",
                     "CRITICAL"
                  ],
                  "event_name":"System",
                  "log_group_name":"System",
                  "log_stream_name":"{instance_id}",
                  "retention_in_days":30
               }
            ]
         }
      }
   },
   "metrics":{
      "aggregation_dimensions":[
         [
            "InstanceId"
         ]
      ],
      "append_dimensions":{
         "AutoScalingGroupName":"${aws:AutoScalingGroupName}",
         "ImageId":"${aws:ImageId}",
         "InstanceId":"${aws:InstanceId}",
         "InstanceType":"${aws:InstanceType}"
      },
      "metrics_collected":{
         "LogicalDisk":{
            "measurement":[
               "% Free Space"
            ],
            "metrics_collection_interval":60,
            "resources":[
               "*"
            ]
         },
         "Memory":{
            "measurement":[
               "% Committed Bytes In Use"
            ],
            "metrics_collection_interval":60
         },
         "statsd":{
            "metrics_aggregation_interval":60,
            "metrics_collection_interval":10,
            "service_address":":8125"
         }
      }
   }
}
```

4. 啟動服務, 載入AWS Systems Manager名為 “AmazonCloudWatch-windows”的設定

```powershell
& "C:\Program Files\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1" -a fetch-config -m ec2 -s -c ssm:AmazonCloudWatch-windows
```

5.編輯保留設定 資料要留多久

![](https://hackmd.io/_uploads/SyV1zhepn.png)
