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 (PDF).

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).

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 from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

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 or update an Amazon CloudWatch alarm and associate it with the specified metric, metric math expression, anomaly detection model, or Metrics Insights query.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Import the SDK and client modules and call the API.

import { PutMetricAlarmCommand } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; const run = async () => { // This alarm triggers when CPUUtilization exceeds 70% for one minute. const command = new PutMetricAlarmCommand({ AlarmName: process.env.CLOUDWATCH_ALARM_NAME, // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm. 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: process.env.EC2_INSTANCE_ID, // Set the value of EC_INSTANCE_ID to the Id of an existing Amazon EC2 instance. }, ], Unit: "Percent", }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDK for JavaScript (v2)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// 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)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Import the SDK and client modules and call the API.

import { DeleteAlarmsCommand } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; const run = async () => { const command = new DeleteAlarmsCommand({ AlarmNames: [process.env.CLOUDWATCH_ALARM_NAME], // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm. }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDK for JavaScript (v2)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

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)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Import the SDK and client modules and call the API.

import { DescribeAlarmsCommand } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; const run = async () => { const command = new DescribeAlarmsCommand({ AlarmNames: [process.env.CLOUDWATCH_ALARM_NAME], // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm. }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDK for JavaScript (v2)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// 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)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Import the SDK and client modules and call the API.

import { DisableAlarmActionsCommand } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; const run = async () => { const command = new DisableAlarmActionsCommand({ AlarmNames: process.env.CLOUDWATCH_ALARM_NAME, // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm. }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDK for JavaScript (v2)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

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)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Import the SDK and client modules and call the API.

import { EnableAlarmActionsCommand } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; const run = async () => { const command = new EnableAlarmActionsCommand({ AlarmNames: [process.env.CLOUDWATCH_ALARM_NAME], // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm. }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDK for JavaScript (v2)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

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 the metadata for Amazon CloudWatch metrics. To get data for a metric, use the GetMetricData or GetMetricStatistics actions.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Import the SDK and client modules and call the API.

import { ListMetricsCommand } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; export const main = () => { // Use the AWS console to see available namespaces and metric names. Custom metrics can also be created. // https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/viewing_metrics_with_cloudwatch.html const command = new ListMetricsCommand({ Dimensions: [ { Name: "LogGroupName", }, ], MetricName: "IncomingLogEvents", Namespace: "AWS/Logs", }); return client.send(command); };

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDK for JavaScript (v2)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// 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 publish metric data points to Amazon CloudWatch.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Import the SDK and client modules and call the API.

import { PutMetricDataCommand } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; const run = async () => { // See https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_PutMetricData.html#API_PutMetricData_RequestParameters // and https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html // for more information about the parameters in this command. const command = new PutMetricDataCommand({ MetricData: [ { MetricName: "PAGES_VISITED", Dimensions: [ { Name: "UNIQUE_PAGES", Value: "URLS", }, ], Unit: "None", Value: 1.0, }, ], Namespace: "SITE/TRAFFIC", }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();

Create the client in a separate module and export it.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDK for JavaScript (v2)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// 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)); } });