The reason your code isn't returning any data is likely because the metric name "MemoryUtilization" is not the correct metric name used by the CloudWatch Agent in the CWAgent namespace. In the CWAgent namespace, the memory utilization metric is typically named "mem_used_percent".
Additionally, the Period you specified is 3600 seconds (1 hour), which may not align with the granularity of the data collected by the CloudWatch Agent. The CloudWatch Agent usually collects metrics at 1-minute intervals. Therefore, setting the period to 60 seconds might yield better results.
Here's the corrected code:
import { CloudWatchClient, GetMetricStatisticsCommand } from "@aws-sdk/client-cloudwatch";
const client = new CloudWatchClient({ region: "eu-central-1" });
const params = {
MetricName: "mem_used_percent", // Corrected metric name
Namespace: "CWAgent",
Dimensions: [
{
Name: "InstanceId",
Value: "i-0c39080034373b0b9", // Replace with your actual instance ID
},
],
StartTime: new Date(Date.now() - 24 * 60 * 60 * 1000), // 24 hours ago
EndTime: new Date(),
Period: 60, // Set to 1-minute interval to match data granularity
Statistics: ["Average"],
};
async function getMemoryStats() {
try {
const data = await client.send(new GetMetricStatisticsCommand(params));
if (!data.Datapoints || data.Datapoints.length === 0) {
console.log("No data points received");
} else {
console.log("Data points received:");
console.log(JSON.stringify(data.Datapoints, null, 2));
}
} catch (err) {
console.error("Error fetching memory statistics:", err);
}
}
getMemoryStats();
Explanation:
- Metric Name: Changed from
"MemoryUtilization" to "mem_used_percent", which is the correct metric name used by the CloudWatch Agent for memory utilization.
- Period: Adjusted from
3600 (1 hour) to 60 (1 minute) to match the data collection interval of the CloudWatch Agent.
- Error Handling: Enhanced error checking to inform you if no data points are received.
Additional Steps:
To verify the exact metric names and dimensions available for your instance, you can list all metrics in the CWAgent namespace using the ListMetricsCommand. This can help ensure you're using the correct metric name and dimensions. Here's how you can do that:
import { CloudWatchClient, ListMetricsCommand } from "@aws-sdk/client-cloudwatch";
const client = new CloudWatchClient({ region: "eu-central-1" });
async function listMetrics() {
try {
const data = await client.send(
new ListMetricsCommand({
Namespace: "CWAgent",
})
);
console.log("Available metrics in 'CWAgent' namespace:");
console.log(JSON.stringify(data.Metrics, null, 2));
} catch (err) {
console.error("Error listing metrics:", err);
}
}
listMetrics();
Tips:
- AWS Credentials: Ensure that your AWS credentials are properly configured and the IAM user or role has permissions to access CloudWatch metrics.
- Instance ID: Double-check the instance ID to make sure it's correct and that the CloudWatch Agent is running on that instance.
- Time Range: Verify that the
StartTime and EndTime are correct and that data is available within that range.
- Metric Data Availability: You can also check the CloudWatch console to see if the metric data is being reported as expected.
By making these adjustments, your code should successfully retrieve and display the memory utilization statistics from CloudWatch for your EC2 instance.