CloudWatch examples using SDK for JavaScript V3 - Amazon SDK for JavaScript
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China.

The Amazon SDK for JavaScript V3 API Reference Guide describes in detail all the API operations for the Amazon SDK for JavaScript version 3 (V3).

Starting October 1, 2022, Amazon SDK for JavaScript (v3) will end support for Internet Explorer 11 (IE 11). For details, see Announcing the end of support for Internet Explorer 11 in the Amazon SDK for JavaScript (v3).

CloudWatch examples using SDK for JavaScript V3

The following code examples show you how to perform actions and implement common scenarios by using the Amazon SDK for JavaScript V3 with CloudWatch.

Actions are code excerpts that show you how to call individual CloudWatch functions.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple CloudWatch functions.

Each example includes a link to GitHub, where you can find instructions on how to set up and run the code in context.

Topics

Actions

The following code example shows how to create an Amazon CloudWatch alarm that watches a metric.

SDK for JavaScript V3
Tip

To learn how to set up and run this example, see GitHub.

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon CloudWatch service client object. export const cwClient = new CloudWatchClient({ region: REGION });

Import the SDK and client modules and call the API.

// Import required AWS SDK clients and commands for Node.js import { PutMetricAlarmCommand } from "@aws-sdk/client-cloudwatch"; import { cwClient } from "./libs/cloudWatchClient.js"; // Set the parameters export const params = { AlarmName: "Web_Server_CPU_Utilization", ComparisonOperator: "GreaterThanThreshold", EvaluationPeriods: 1, MetricName: "CPUUtilization", Namespace: "AWS/EC2", Period: 60, Statistic: "Average", Threshold: 70.0, ActionsEnabled: false, AlarmDescription: "Alarm when server CPU exceeds 70%", Dimensions: [ { Name: "InstanceId", Value: "INSTANCE_ID", }, ], Unit: "Percent", }; export const run = async () => { try { const data = await cwClient.send(new PutMetricAlarmCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run();
SDK for JavaScript V2
Tip

To learn how to set up and run this example, see GitHub.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create CloudWatch service object var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); var params = { AlarmName: 'Web_Server_CPU_Utilization', ComparisonOperator: 'GreaterThanThreshold', EvaluationPeriods: 1, MetricName: 'CPUUtilization', Namespace: 'AWS/EC2', Period: 60, Statistic: 'Average', Threshold: 70.0, ActionsEnabled: false, AlarmDescription: 'Alarm when server CPU exceeds 70%', Dimensions: [ { Name: 'InstanceId', Value: 'INSTANCE_ID' }, ], Unit: 'Percent' }; cw.putMetricAlarm(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

The following code example shows how to delete Amazon CloudWatch alarms.

SDK for JavaScript V3
Tip

To learn how to set up and run this example, see GitHub.

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon CloudWatch service client object. export const cwClient = new CloudWatchClient({ region: REGION });

Import the SDK and client modules and call the API.

// Import required AWS SDK clients and commands for Node.js import { DeleteAlarmsCommand } from "@aws-sdk/client-cloudwatch"; import { cwClient } from "./libs/cloudWatchClient.js"; // Set the parameters export const params = { AlarmNames: "ALARM_NAME" }; // e.g., "Web_Server_CPU_Utilization" export const run = async () => { try { const data = await cwClient.send(new DeleteAlarmsCommand(params)); console.log("Success, alarm deleted; requestID:", data); return data; } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run();
SDK for JavaScript V2
Tip

To learn how to set up and run this example, see GitHub.

Import the SDK and client modules and call the API.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create CloudWatch service object var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); var params = { AlarmNames: ['Web_Server_CPU_Utilization'] }; cw.deleteAlarms(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

The following code example shows how to describe Amazon CloudWatch alarms for a metric.

SDK for JavaScript V3
Tip

To learn how to set up and run this example, see GitHub.

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon CloudWatch service client object. export const cwClient = new CloudWatchClient({ region: REGION });

Import the SDK and client modules and call the API.

// Import required AWS SDK clients and commands for Node.js import { DescribeAlarmsCommand } from "@aws-sdk/client-cloudwatch"; import { cwClient } from "./libs/cloudWatchClient.js"; // Set the parameters export const params = { StateValue: "INSUFFICIENT_DATA" }; export const run = async () => { try { const data = await cwClient.send(new DescribeAlarmsCommand(params)); console.log("Success", data); data.MetricAlarms.forEach(function (item) { console.log(item.AlarmName); }); return data; } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run();
SDK for JavaScript V2
Tip

To learn how to set up and run this example, see GitHub.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create CloudWatch service object var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); cw.describeAlarms({StateValue: 'INSUFFICIENT_DATA'}, function(err, data) { if (err) { console.log("Error", err); } else { // List the names of all current alarms in the console data.MetricAlarms.forEach(function (item, index, array) { console.log(item.AlarmName); }); } });

The following code example shows how to disable Amazon CloudWatch alarm actions.

SDK for JavaScript V3
Tip

To learn how to set up and run this example, see GitHub.

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon CloudWatch service client object. export const cwClient = new CloudWatchClient({ region: REGION });

Import the SDK and client modules and call the API.

// Import required AWS SDK clients and commands for Node.js import { DisableAlarmActionsCommand } from "@aws-sdk/client-cloudwatch"; import { cwClient } from "./libs/cloudWatchClient.js"; // Set the parameters export const params = { AlarmNames: "ALARM_NAME" }; // e.g., "Web_Server_CPU_Utilization" export const run = async () => { try { const data = await cwClient.send(new DisableAlarmActionsCommand(params)); console.log("Success, alarm disabled:", data); return data; } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run();
SDK for JavaScript V2
Tip

To learn how to set up and run this example, see GitHub.

Import the SDK and client modules and call the API.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create CloudWatch service object var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); cw.disableAlarmActions({AlarmNames: ['Web_Server_CPU_Utilization']}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

The following code example shows how to enable Amazon CloudWatch alarm actions.

SDK for JavaScript V3
Tip

To learn how to set up and run this example, see GitHub.

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon CloudWatch service client object. export const cwClient = new CloudWatchClient({ region: REGION });

Import the SDK and client modules and call the API.

// Import required AWS SDK clients and commands for Node.js import { PutMetricAlarmCommand, EnableAlarmActionsCommand, } from "@aws-sdk/client-cloudwatch"; import { cwClient } from "./libs/cloudWatchClient.js"; // Set the parameters export const params = { AlarmName: "ALARM_NAME", //ALARM_NAME ComparisonOperator: "GreaterThanThreshold", EvaluationPeriods: 1, MetricName: "CPUUtilization", Namespace: "AWS/EC2", Period: 60, Statistic: "Average", Threshold: 70.0, ActionsEnabled: true, AlarmActions: ["ACTION_ARN"], //e.g., "arn:aws:automate:us-east-1:ec2:stop" AlarmDescription: "Alarm when server CPU exceeds 70%", Dimensions: [ { Name: "InstanceId", Value: "INSTANCE_ID", }, ], Unit: "Percent", }; export const run = async () => { try { const data = await cwClient.send(new PutMetricAlarmCommand(params)); console.log("Alarm action added; RequestID:", data); return data; const paramsEnableAlarmAction = { AlarmNames: [params.AlarmName], }; try { const data = await cwClient.send( new EnableAlarmActionsCommand(paramsEnableAlarmAction) ); console.log("Alarm action enabled; RequestID:", data.$metadata.requestId); } catch (err) { console.log("Error", err); return data; } } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run();
SDK for JavaScript V2
Tip

To learn how to set up and run this example, see GitHub.

Import the SDK and client modules and call the API.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create CloudWatch service object var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); var params = { AlarmName: 'Web_Server_CPU_Utilization', ComparisonOperator: 'GreaterThanThreshold', EvaluationPeriods: 1, MetricName: 'CPUUtilization', Namespace: 'AWS/EC2', Period: 60, Statistic: 'Average', Threshold: 70.0, ActionsEnabled: true, AlarmActions: ['ACTION_ARN'], AlarmDescription: 'Alarm when server CPU exceeds 70%', Dimensions: [ { Name: 'InstanceId', Value: 'INSTANCE_ID' }, ], Unit: 'Percent' }; cw.putMetricAlarm(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Alarm action added", data); var paramsEnableAlarmAction = { AlarmNames: [params.AlarmName] }; cw.enableAlarmActions(paramsEnableAlarmAction, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Alarm action enabled", data); } }); } });

The following code example shows how to list Amazon CloudWatch metrics.

SDK for JavaScript V3
Tip

To learn how to set up and run this example, see GitHub.

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon CloudWatch service client object. export const cwClient = new CloudWatchClient({ region: REGION });

Import the SDK and client modules and call the API.

// Import required AWS SDK clients and commands for Node.js import { ListMetricsCommand } from "@aws-sdk/client-cloudwatch"; import { cwClient } from "./libs/cloudWatchClient.js"; // Set the parameters export const params = { Dimensions: [ { Name: "LogGroupName" /* required */, }, ], MetricName: "IncomingLogEvents", Namespace: "AWS/Logs", }; export const run = async () => { try { const data = await cwClient.send(new ListMetricsCommand(params)); console.log("Success. Metrics:", JSON.stringify(data.Metrics)); return data; } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run();
SDK for JavaScript V2
Tip

To learn how to set up and run this example, see GitHub.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create CloudWatch service object var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); var params = { Dimensions: [ { Name: 'LogGroupName', /* required */ }, ], MetricName: 'IncomingLogEvents', Namespace: 'AWS/Logs' }; cw.listMetrics(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Metrics", JSON.stringify(data.Metrics)); } });

The following code example shows how to put data into a Amazon CloudWatch metric.

SDK for JavaScript V3
Tip

To learn how to set up and run this example, see GitHub.

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon CloudWatch service client object. export const cwClient = new CloudWatchClient({ region: REGION });

Import the SDK and client modules and call the API.

// Import required AWS SDK clients and commands for Node.js import { PutMetricDataCommand } from "@aws-sdk/client-cloudwatch"; import { cwClient } from "./libs/cloudWatchClient.js"; // Set the parameters export const params = { MetricData: [ { MetricName: "PAGES_VISITED", Dimensions: [ { Name: "UNIQUE_PAGES", Value: "URLS", }, ], Unit: "None", Value: 1.0, }, ], Namespace: "SITE/TRAFFIC", }; export const run = async () => { try { const data = await cwClient.send(new PutMetricDataCommand(params)); console.log("Success", data.$metadata.requestId); return data; } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run();
SDK for JavaScript V2
Tip

To learn how to set up and run this example, see GitHub.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create CloudWatch service object var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); // Create parameters JSON for putMetricData var params = { MetricData: [ { MetricName: 'PAGES_VISITED', Dimensions: [ { Name: 'UNIQUE_PAGES', Value: 'URLS' }, ], Unit: 'None', Value: 1.0 }, ], Namespace: 'SITE/TRAFFIC' }; cw.putMetricData(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", JSON.stringify(data)); } });