id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
acw-ug-771
acw-ug.pdf
771
metrics that the CloudWatch agent can already collect with the additional metrics from collectd, you can better monitor, analyze, and troubleshoot your systems and applications. For more information about collectd, see collectd - The system statistics collection daemon. You use the collectd software to send the metrics to the CloudWatch agent. For the collectd metrics, the CloudWatch agent acts as the server while the collectd plugin acts as the client. The collectd software is not installed automatically on every server. On a server running Amazon Linux 2, follow these steps to install collectd sudo amazon-linux-extras install collectd For information about installing collectd on other systems, see the Download page for collectd. To collect these custom metrics, add a "collectd": {} line to the metrics_collected section of the agent configuration file. You can add this line manually. If you use the wizard to create the configuration file, it is done for you. For more information, see Create the CloudWatch agent configuration file. Optional parameters are also available. If you are using collectd and you do not use /etc/ collectd/auth_file as your collectd_auth_file, you must set some of these options. • service_address: The service address to which the CloudWatch agent should listen. The format is "udp://ip:port. The default is udp://127.0.0.1:25826. • name_prefix: A prefix to attach to the beginning of the name of each collectd metric. The default is collectd_. The maximum length is 255 characters. • collectd_security_level: Sets the security level for network communication. The default is encrypt. encrypt specifies that only encrypted data is accepted. sign specifies that only signed and encrypted data is accepted. none specifies that all data is accepted. If you specify a value for collectd_auth_file, encrypted data is decrypted if possible. For more information, see Client setup and Possible interactions in the collectd Wiki. • collectd_auth_file Sets a file in which user names are mapped to passwords. These passwords are used to verify signatures and to decrypt encrypted network packets. If given, signed data is verified and encrypted packets are decrypted. Otherwise, signed data is accepted without checking the signature and encrypted data cannot be decrypted. Manually create or edit the CloudWatch agent configuration file 2688 Amazon CloudWatch User Guide The default is /etc/collectd/auth_file. If collectd_security_level is set to none, this is optional. If you set collectd_security_level to encrypt or sign, you must specify collectd_auth_file. For the format of the auth file, each line is a user name followed by a colon and any number of spaces followed by the password. For example: user1: user1_password user2: user2_password • collectd_typesdb: A list of one or more files that contain the dataset descriptions. The list must be surrounded by brackets, even if there is just one entry in the list. Each entry in the list must be surrounded by double quotes. If there are multiple entries, separate them with commas. The default on Linux servers is ["/usr/share/collectd/types.db"]. The default on macOs computers depends on the version of collectd. For example, ["/usr/local/Cellar/ collectd/5.12.0/share/collectd/types.db"]. For more information, see https://www.collectd.org/documentation/manpages/types.db.html. • metrics_aggregation_interval: How often in seconds CloudWatch aggregates metrics into single data points. The default is 60 seconds. The range is 0 to 172,000. Setting it to 0 disables the aggregation of collectd metrics. The following is an example of the collectd section of the agent configuration file. { "metrics":{ "metrics_collected":{ "collectd":{ "name_prefix":"My_collectd_metrics_", "metrics_aggregation_interval":120 } } } } Manually create or edit the CloudWatch agent configuration file 2689 Amazon CloudWatch User Guide Viewing collectd metrics imported by the CloudWatch agent After importing collectd metrics into CloudWatch, you can view these metrics as time series graphs, and create alarms that can watch these metrics and notify you if they breach a threshold that you specify. The following procedure shows how to view collectd metrics as a time series graph. For more information about setting alarms, see Using Amazon CloudWatch alarms. To view collectd metrics in the CloudWatch console 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Metrics. 3. Choose the namespace for the metrics collected by the agent. By default, this is CWAgent, but you may have specified a different namespace in the CloudWatch agent configuration file. 4. Choose a metric dimension (for example, Per-Instance Metrics). 5. The All metrics tab displays all metrics for that dimension in the namespace. You can do the following: a. To graph a metric, select the check box next to the metric. To select all metrics, select the check box in the heading row of the table. To sort the table, use the column heading. To filter by resource, choose the resource ID and then choose Add to search. To filter by metric, choose the metric name and then choose Add to search. b. c. d. 6. (Optional) To add this graph to a CloudWatch dashboard, choose Actions, Add to dashboard.
acw-ug-772
acw-ug.pdf
772
The All metrics tab displays all metrics for that dimension in the namespace. You can do the following: a. To graph a metric, select the check box next to the metric. To select all metrics, select the check box in the heading row of the table. To sort the table, use the column heading. To filter by resource, choose the resource ID and then choose Add to search. To filter by metric, choose the metric name and then choose Add to search. b. c. d. 6. (Optional) To add this graph to a CloudWatch dashboard, choose Actions, Add to dashboard. Set up and configure Prometheus metrics collection on Amazon EC2 instances The following sections explain how to install the CloudWatch agent with Prometheus monitoring on EC2 instances, and how to configure the agent to scrape additional targets. It also provides tutorials for setting up sample workloads to use testing with Prometheus monitoring. Both Linux and Windows instances are supported. For information about the operating systems supported by the CloudWatch agent, see Collect metrics, logs, and traces with the CloudWatch agent VPC security group requirements If you are using a VPC, the following requirements apply. Manually create or edit the CloudWatch agent configuration file 2690 Amazon CloudWatch User Guide • The ingress rules of the security groups for the Prometheus workloads must open the Prometheus ports to the CloudWatch agent for scraping the Prometheus metrics by the private IP. • The egress rules of the security group for the CloudWatch agent must allow the CloudWatch agent to connect to the Prometheus workloads' port by private IP. Topics • Step 1: Install the CloudWatch agent • Step 2: Scrape Prometheus sources and import metrics • Example: Set up Java/JMX sample workloads for Prometheus metric testing Step 1: Install the CloudWatch agent The first step is to install the CloudWatch agent on the EC2 instance. For instructions, see Install the CloudWatch agent. Step 2: Scrape Prometheus sources and import metrics The CloudWatch agent with Prometheus monitoring needs two configurations to scrape the Prometheus metrics. One is for the standard Prometheus configurations as documented in <scrape_config>in the Prometheus documentation. The other is for the CloudWatch agent configuration. Prometheus scrape configuration The CloudWatch agent supports the standard Prometheus scrape configurations as documented in <scrape_config> in the Prometheus documentation. You can edit this section to update the configurations that are already in this file, and add additional Prometheus scraping targets. A sample configuration file contains the following global configuration lines: PS C:\ProgramData\Amazon\AmazonCloudWatchAgent> cat prometheus.yaml global: scrape_interval: 1m scrape_timeout: 10s scrape_configs: - job_name: MY_JOB sample_limit: 10000 file_sd_configs: Manually create or edit the CloudWatch agent configuration file 2691 Amazon CloudWatch User Guide - files: ["C:\\ProgramData\\Amazon\\AmazonCloudWatchAgent\\prometheus_sd_1.yaml", "C:\\ProgramData\\Amazon\\AmazonCloudWatchAgent\\prometheus_sd_2.yaml"] The global section specifies parameters that are valid in all configuration contexts. They also serve as defaults for other configuration sections. It contains the following parameters: • scrape_interval— Defines how frequently to scrape targets. • scrape_timeout— Defines how long to wait before a scrape request times out. The scrape_configs section specifies a set of targets and parameters that define how to scrape them. It contains the following parameters: • job_name— The job name assigned to scraped metrics by default. • sample_limit— Per-scrape limit on the number of scraped samples that will be accepted. • file_sd_configs— List of file service discovery configurations. It reads a set of files containing a list of zero or more static configs. The file_sd_configs section contains a files parameter which defines patterns for files from which target groups are extracted. The CloudWatch agent supports the following service discovery configuration types. static_config Allows specifying a list of targets and a common label set for them. It is the canonical way to specify static targets in a scrape configuration. The following is a sample static config to scrape Prometheus metrics from a local host. Metrics can also be scraped from other servers if the Prometheus port is open to the server where the agent runs. PS C:\ProgramData\Amazon\AmazonCloudWatchAgent> cat prometheus_sd_1.yaml - targets: - 127.0.0.1:9404 labels: key1: value1 key2: value2 This example contains the following parameters: • targets— The targets scraped by the static config. • labels— Labels assigned to all metrics that are scraped from the targets. Manually create or edit the CloudWatch agent configuration file 2692 Amazon CloudWatch User Guide ec2_sd_config Allows retrieving scrape targets from Amazon EC2 instances. The following is a sample ec2_sd_config to scrape Prometheus metrics from a list of EC2 instances. The Prometheus ports of these instances have to open to the server where the CloudWatch agent runs. The IAM role for the EC2 instance where the CloudWatch agent runs must include the ec2:DescribeInstance permission. For example, you could attach the managed policy AmazonEC2ReadOnlyAccess to the instance running the CloudWatch agent. PS C:\ProgramData\Amazon\AmazonCloudWatchAgent> cat prometheus.yaml global: scrape_interval: 1m scrape_timeout: 10s scrape_configs: - job_name: MY_JOB sample_limit: 10000
acw-ug-773
acw-ug.pdf
773
the CloudWatch agent configuration file 2692 Amazon CloudWatch User Guide ec2_sd_config Allows retrieving scrape targets from Amazon EC2 instances. The following is a sample ec2_sd_config to scrape Prometheus metrics from a list of EC2 instances. The Prometheus ports of these instances have to open to the server where the CloudWatch agent runs. The IAM role for the EC2 instance where the CloudWatch agent runs must include the ec2:DescribeInstance permission. For example, you could attach the managed policy AmazonEC2ReadOnlyAccess to the instance running the CloudWatch agent. PS C:\ProgramData\Amazon\AmazonCloudWatchAgent> cat prometheus.yaml global: scrape_interval: 1m scrape_timeout: 10s scrape_configs: - job_name: MY_JOB sample_limit: 10000 ec2_sd_configs: - region: us-east-1 port: 9404 filters: - name: instance-id values: - i-98765432109876543 - i-12345678901234567 This example contains the following parameters: • region— The AWS Region where the target EC2 instance is. If you leave this blank, the Region from the instance metadata is used. • port— The port to scrape metrics from. • filters— Optional filters to use to filter the instance list. This example filters based on EC2 instance IDs. For more criteria that you can filter on, see DescribeInstances. CloudWatch agent configuration for Prometheus The CloudWatch agent configuration file includes prometheus sections under both logs and metrics_collected. It includes the following parameters. • cluster_name— specifies the cluster name to be added as a label in the log event. This field is optional. • log_group_name— specifies the log group name for the scraped Prometheus metrics. Manually create or edit the CloudWatch agent configuration file 2693 Amazon CloudWatch User Guide • prometheus_config_path— specifies the Prometheus scrape configuration file path. • emf_processor— specifies the embedded metric format processor configuration. For more information about embedded metric format, see Embedding metrics within logs. The emf_processor section can contain the following parameters: • metric_declaration_dedup— It set to true, the de-duplication function for the embedded metric format metrics is enabled. • metric_namespace— Specifies the metric namespace for the emitted CloudWatch metrics. • metric_unit— Specifies the metric name:metric unit map. For information about supported metric units, see MetricDatum. • metric_declaration— are sections that specify the array of logs with embedded metric format to be generated. There are metric_declaration sections for each Prometheus source that the CloudWatch agent imports from by default. These sections each include the following fields: • source_labels specifies the value of the labels that are checked by the label_matcher line. • label_matcher is a regular expression that checks the value of the labels listed in source_labels. The metrics that match are enabled for inclusion in the embedded metric format sent to CloudWatch. • metric_selectors is a regular expression that specifies the metrics to be collected and sent to CloudWatch. • dimensions is the list of labels to be used as CloudWatch dimensions for each selected metric. The following is an example CloudWatch agent configuration for Prometheus. { "logs":{ "metrics_collected":{ "prometheus":{ "cluster_name":"prometheus-cluster", "log_group_name":"Prometheus", "prometheus_config_path":"C:\\ProgramData\\Amazon\\AmazonCloudWatchAgent\ \prometheus.yaml", "emf_processor":{ "metric_declaration_dedup":true, "metric_namespace":"CWAgent-Prometheus", Manually create or edit the CloudWatch agent configuration file 2694 Amazon CloudWatch User Guide "metric_unit":{ "jvm_threads_current": "Count", "jvm_gc_collection_seconds_sum": "Milliseconds" }, "metric_declaration":[ { "source_labels":[ "job", "key2" ], "label_matcher":"MY_JOB;^value2", "dimensions":[ [ "key1", "key2" ], [ "key2" ] ], "metric_selectors":[ "^jvm_threads_current$", "^jvm_gc_collection_seconds_sum$" ] } ] } } } } } The previous example configures an embedded metric format section to be sent as a log event if the following conditions are met: • The value of the label job is MY_JOB • The value of the label key2 is value2 • The Prometheus metrics jvm_threads_current and jvm_gc_collection_seconds_sum contains both job and key2 labels. The log event that is sent includes the following highlighted section. { Manually create or edit the CloudWatch agent configuration file 2695 Amazon CloudWatch User Guide "CloudWatchMetrics": [ { "Metrics": [ { "Unit": "Count", "Name": "jvm_threads_current" }, { "Unit": "Milliseconds", "Name": "jvm_gc_collection_seconds_sum" } ], "Dimensions": [ [ "key1", "key2" ], [ "key2" ] ], "Namespace": "CWAgent-Prometheus" } ], "ClusterName": "prometheus-cluster", "InstanceId": "i-0e45bd06f196096c8", "Timestamp": "1607966368109", "Version": "0", "host": "EC2AMAZ-PDDOIUM", "instance": "127.0.0.1:9404", "jvm_threads_current": 2, "jvm_gc_collection_seconds_sum": 0.006000000000000002, "prom_metric_type": "gauge", ... } Example: Set up Java/JMX sample workloads for Prometheus metric testing JMX Exporter is an official Prometheus exporter that can scrape and expose JMX mBeans as Prometheus metrics. For more information, see prometheus/jmx_exporter. The CloudWatch agent can collect predefined Prometheus metrics from Java Virtual Machine (JVM), Hjava, and Tomcat (Catalina), from a JMX exporter on EC2 instances. Manually create or edit the CloudWatch agent configuration file 2696 Amazon CloudWatch User Guide Step 1: Install the CloudWatch agent The first step is to install the CloudWatch agent on the EC2 instance. For instructions, see Install the CloudWatch agent. Step 2: Start the Java/JMX workload The next step is to start the Java/JMX workload. First, download the latest JMX exporter jar file from the following location: prometheus/ jmx_exporter. Use the jar for your sample application The example commands in the following sections use SampleJavaApplication-1.0- SNAPSHOT.jar as the jar file. Replace
acw-ug-774
acw-ug.pdf
774
Tomcat (Catalina), from a JMX exporter on EC2 instances. Manually create or edit the CloudWatch agent configuration file 2696 Amazon CloudWatch User Guide Step 1: Install the CloudWatch agent The first step is to install the CloudWatch agent on the EC2 instance. For instructions, see Install the CloudWatch agent. Step 2: Start the Java/JMX workload The next step is to start the Java/JMX workload. First, download the latest JMX exporter jar file from the following location: prometheus/ jmx_exporter. Use the jar for your sample application The example commands in the following sections use SampleJavaApplication-1.0- SNAPSHOT.jar as the jar file. Replace these parts of the commands with the jar for your application. Prepare the JMX exporter configuration The config.yaml file is the JMX exporter configuration file. For more information, see Configuration in the JMX exporter documentation. Here is a sample configuration for Java and Tomcat. --- lowercaseOutputName: true lowercaseOutputLabelNames: true rules: - pattern: 'java.lang<type=OperatingSystem><>(FreePhysicalMemorySize| TotalPhysicalMemorySize|FreeSwapSpaceSize|TotalSwapSpaceSize|SystemCpuLoad| ProcessCpuLoad|OpenFileDescriptorCount|AvailableProcessors)' name: java_lang_OperatingSystem_$1 type: GAUGE - pattern: 'java.lang<type=Threading><>(TotalStartedThreadCount|ThreadCount)' name: java_lang_threading_$1 type: GAUGE - pattern: 'Catalina<type=GlobalRequestProcessor, name=\"(\w+-\w+)-(\d+)\"><>(\w+)' name: catalina_globalrequestprocessor_$3_total labels: Manually create or edit the CloudWatch agent configuration file 2697 Amazon CloudWatch port: "$2" protocol: "$1" help: Catalina global $3 type: COUNTER User Guide - pattern: 'Catalina<j2eeType=Servlet, WebModule=//([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[- a-zA-Z0-9+&@#/%=~_|]), name=([-a-zA-Z0-9+/$%~_-|!.]*), J2EEApplication=none, J2EEServer=none><>(requestCount|maxTime|processingTime|errorCount)' name: catalina_servlet_$3_total labels: module: "$1" servlet: "$2" help: Catalina servlet $3 total type: COUNTER - pattern: 'Catalina<type=ThreadPool, name="(\w+-\w+)-(\d+)"><>(currentThreadCount| currentThreadsBusy|keepAliveCount|pollerThreadCount|connectionCount)' name: catalina_threadpool_$3 labels: port: "$2" protocol: "$1" help: Catalina threadpool $3 type: GAUGE - pattern: 'Catalina<type=Manager, host=([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA- Z0-9+&@#/%=~_|]), context=([-a-zA-Z0-9+/$%~_-|!.]*)><>(processingTime|sessionCounter| rejectedSessions|expiredSessions)' name: catalina_session_$3_total labels: context: "$2" host: "$1" help: Catalina session $3 total type: COUNTER - pattern: ".*" Start the Java application with the Prometheus exporter Start the sample application. This will emit Prometheus metrics to port 9404. Be sure to replace the entry point com.gubupt.sample.app.App with the correct information for your sample java application. On Linux, enter the following command. Manually create or edit the CloudWatch agent configuration file 2698 Amazon CloudWatch User Guide $ nohup java -javaagent:./jmx_prometheus_javaagent-0.14.0.jar=9404:./config.yaml -cp ./SampleJavaApplication-1.0-SNAPSHOT.jar com.gubupt.sample.app.App & On Windows, enter the following command. PS C:\> java -javaagent:.\jmx_prometheus_javaagent-0.14.0.jar=9404:.\config.yaml -cp . \SampleJavaApplication-1.0-SNAPSHOT.jar com.gubupt.sample.app.App Verify the Prometheus metrics emission Verify that Prometheus metrics are being emitted. On Linux, enter the following command. $ curl localhost:9404 On Windows, enter the following command. PS C:\> curl http://localhost:9404 Sample output on Linux: StatusCode : 200 StatusDescription : OK Content : # HELP jvm_classes_loaded The number of classes that are currently loaded in the JVM # TYPE jvm_classes_loaded gauge jvm_classes_loaded 2526.0 # HELP jvm_classes_loaded_total The total number of class... RawContent : HTTP/1.1 200 OK Content-Length: 71908 Content-Type: text/plain; version=0.0.4; charset=utf-8 Date: Fri, 18 Dec 2020 16:38:10 GMT # HELP jvm_classes_loaded The number of classes that are currentl... Forms : {} Headers : {[Content-Length, 71908], [Content-Type, text/plain; version=0.0.4; charset=utf-8], [Date, Fri, 18 Dec 2020 16:38:10 GMT]} Images : {} InputFields : {} Manually create or edit the CloudWatch agent configuration file 2699 Amazon CloudWatch User Guide Links : {} ParsedHtml : System.__ComObject RawContentLength : 71908 Step 3: Configure the CloudWatch agent to scrape Prometheus metrics Next, set up the Prometheus scrape configuration in the CloudWatch agent configuration file. To set up the Prometheus scrape configuration for the Java/JMX example 1. Set up the configuration for file_sd_config and static_config. On Linux, enter the following command. $ cat /opt/aws/amazon-cloudwatch-agent/var/prometheus.yaml global: scrape_interval: 1m scrape_timeout: 10s scrape_configs: - job_name: jmx sample_limit: 10000 file_sd_configs: - files: [ "/opt/aws/amazon-cloudwatch-agent/var/prometheus_file_sd.yaml" ] On Windows, enter the following command. PS C:\ProgramData\Amazon\AmazonCloudWatchAgent> cat prometheus.yaml global: scrape_interval: 1m scrape_timeout: 10s scrape_configs: - job_name: jmx sample_limit: 10000 file_sd_configs: - files: [ "C:\\ProgramData\\Amazon\\AmazonCloudWatchAgent\ \prometheus_file_sd.yaml" ] 2. Set up the scrape targets configuration. On Linux, enter the following command. $ cat /opt/aws/amazon-cloudwatch-agent/var/prometheus_file_sd.yaml Manually create or edit the CloudWatch agent configuration file 2700 Amazon CloudWatch User Guide - targets: - 127.0.0.1:9404 labels: application: sample_java_app os: linux On Windows, enter the following command. PS C:\ProgramData\Amazon\AmazonCloudWatchAgent> cat prometheus_file_sd.yaml - targets: - 127.0.0.1:9404 labels: application: sample_java_app os: windows 3. Set up the Prometheus scrape configuration by ec2_sc_config. Replace your-ec2- instance-id with the correct EC2 instance ID. On Linux, enter the following command. $ cat .\prometheus.yaml global: scrape_interval: 1m scrape_timeout: 10s scrape_configs: - job_name: jmx sample_limit: 10000 ec2_sd_configs: - region: us-east-1 port: 9404 filters: - name: instance-id values: - your-ec2-instance-id On Windows, enter the following command. PS C:\ProgramData\Amazon\AmazonCloudWatchAgent> cat prometheus_file_sd.yaml - targets: - 127.0.0.1:9404 labels: application: sample_java_app Manually create or edit the CloudWatch agent configuration file 2701 Amazon CloudWatch os: windows User Guide 4. Set up the CloudWatch agent configuration. First, navigate to the correct directory. On Linux, it is /opt/aws/amazon-cloudwatch-agent/var/cwagent-config.json. On Windows, it is C:\ProgramData\Amazon\AmazonCloudWatchAgent\cwagent-config.json. The following is a sample configuration with Java/JHX Prometheus metrics defined. Be sure to replace path-to-Prometheus-Scrape-Configuration-file with the correct path. { "agent": { "region": "us-east-1" }, "logs": { "metrics_collected": { "prometheus": { "cluster_name": "my-cluster", "log_group_name": "prometheus-test", "prometheus_config_path": "path-to-Prometheus-Scrape-Configuration-file", "emf_processor": { "metric_declaration_dedup": true, "metric_namespace": "PrometheusTest", "metric_unit":{ "jvm_threads_current": "Count", "jvm_classes_loaded": "Count", "java_lang_operatingsystem_freephysicalmemorysize": "Bytes", "catalina_manager_activesessions":
acw-ug-775
acw-ug.pdf
775
cat prometheus_file_sd.yaml - targets: - 127.0.0.1:9404 labels: application: sample_java_app Manually create or edit the CloudWatch agent configuration file 2701 Amazon CloudWatch os: windows User Guide 4. Set up the CloudWatch agent configuration. First, navigate to the correct directory. On Linux, it is /opt/aws/amazon-cloudwatch-agent/var/cwagent-config.json. On Windows, it is C:\ProgramData\Amazon\AmazonCloudWatchAgent\cwagent-config.json. The following is a sample configuration with Java/JHX Prometheus metrics defined. Be sure to replace path-to-Prometheus-Scrape-Configuration-file with the correct path. { "agent": { "region": "us-east-1" }, "logs": { "metrics_collected": { "prometheus": { "cluster_name": "my-cluster", "log_group_name": "prometheus-test", "prometheus_config_path": "path-to-Prometheus-Scrape-Configuration-file", "emf_processor": { "metric_declaration_dedup": true, "metric_namespace": "PrometheusTest", "metric_unit":{ "jvm_threads_current": "Count", "jvm_classes_loaded": "Count", "java_lang_operatingsystem_freephysicalmemorysize": "Bytes", "catalina_manager_activesessions": "Count", "jvm_gc_collection_seconds_sum": "Seconds", "catalina_globalrequestprocessor_bytesreceived": "Bytes", "jvm_memory_bytes_used": "Bytes", "jvm_memory_pool_bytes_used": "Bytes" }, "metric_declaration": [ { "source_labels": ["job"], "label_matcher": "^jmx$", "dimensions": [["instance"]], "metric_selectors": [ "^jvm_threads_current$", "^jvm_classes_loaded$", "^java_lang_operatingsystem_freephysicalmemorysize$", "^catalina_manager_activesessions$", "^jvm_gc_collection_seconds_sum$", Manually create or edit the CloudWatch agent configuration file 2702 Amazon CloudWatch User Guide "^catalina_globalrequestprocessor_bytesreceived$" ] }, { "source_labels": ["job"], "label_matcher": "^jmx$", "dimensions": [["area"]], "metric_selectors": [ "^jvm_memory_bytes_used$" ] }, { "source_labels": ["job"], "label_matcher": "^jmx$", "dimensions": [["pool"]], "metric_selectors": [ "^jvm_memory_pool_bytes_used$" ] } ] } } }, "force_flush_interval": 5 } } 5. Restart the CloudWatch agent by entering one of the following commands. On Linux, enter the following command. sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch- config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/var/cwagent-config.json On Windows, enter the following command. & "C:\Program Files\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1" -a fetch-config -m ec2 -s -c file:C:\ProgramData\Amazon\AmazonCloudWatchAgent \cwagent-config.json Manually create or edit the CloudWatch agent configuration file 2703 Amazon CloudWatch User Guide Viewing the Prometheus metrics and logs You can now view the Java/JMX metrics being collected. To view the metrics for your sample Java/JMX workload 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. 3. In the Region where your cluster is running, choose Metrics in the left navigation pane. Find the PrometheusTest namespace to see the metrics. To see the CloudWatch Logs events, choose Log groups in the navigation pane. The events are in the log group prometheus-test. Configure CloudWatch agent service and environment names for related entities The CloudWatch agent can send metrics and logs with entity data to support the Explore related pane in the CloudWatch console. The service name or environment name can be configured by the CloudWatch Agent JSON configuration. Note The agent configuration may be overridden. For details about how the agent decides what data to send for related entities, see Using the CloudWatch agent with related telemetry. For metrics, it can be configured at the agent, metrics, or plugin level. For logs it can be configured at the agent, logs, or file level. The most specific configuration is always used. For example if the configuration exists at the agent level and metrics level, then metrics will use the metric configuration, and anything else (logs) will use the agent configuration. The following example shows different ways to configure the service name and environment name. { "agent": { "service.name": "agent-level-service", "deployment.environment": "agent-level-environment" }, "metrics": { "service.name": "metric-level-service", "deployment.environment": "metric-level-environment", Manually create or edit the CloudWatch agent configuration file 2704 Amazon CloudWatch User Guide "metrics_collected": { "statsd": { "service.name": "statsd-level-service", "deployment.environment": "statsd-level-environment", }, "collectd": { "service.name": "collectdd-level-service", "deployment.environment": "collectd-level-environment", } } }, "logs": { "service.name": "log-level-service", "deployment.environment": "log-level-environment", "logs_collected": { "files": { "collect_list": [ { "file_path": "/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch- agent.log", "log_group_name": "amazon-cloudwatch-agent.log", "log_stream_name": "amazon-cloudwatch-agent.log", "service.name": "file-level-service", "deployment.environment": "file-level-environment" } ] } } } } Install the CloudWatch agent with the Amazon CloudWatch Observability EKS add-on or the Helm chart You can use either the Amazon CloudWatch Observability EKS add-on or the Amazon CloudWatch Observability Helm chart to install the CloudWatch Agent and the Fluent-bit agent on an Amazon Install the CloudWatch agent with the Amazon CloudWatch Observability EKS add-on or the Helm chart 2705 Amazon CloudWatch User Guide EKS cluster. You can also use the Helm chart to install the CloudWatch Agent and the Fluent-bit agent on a Kubernetes cluster that is not hosted on Amazon EKS. Using either method on an Amazon EKS cluster enables both Container Insights with enhanced observability for Amazon EKS and CloudWatch Application Signals by default. Both features help you to collect infrastructure metrics, application performance telemetry, and container logs from the cluster. With Container Insights with enhanced observability for Amazon EKS, Container Insights metrics are charged per observation instead of being charged per metric stored or log ingested. For Application Signals, billing is based on inbound requests to your applications, outbound requests from your applications, and each configured service level objective (SLO). Each inbound request received generates one application signal, and each outbound request made generates one application signal. Every SLO creates two application signals per measurement period. For more information about CloudWatch pricing, see Amazon CloudWatch Pricing. Both methods enable Container Insights on both Linux and Windows worker nodes in the Amazon EKS cluster. To enable Container Insights on Windows, you must use version 1.5.0 or later of the Amazon EKS add-on or the Helm chart. Currently, Application Signals
acw-ug-776
acw-ug.pdf
776
Signals, billing is based on inbound requests to your applications, outbound requests from your applications, and each configured service level objective (SLO). Each inbound request received generates one application signal, and each outbound request made generates one application signal. Every SLO creates two application signals per measurement period. For more information about CloudWatch pricing, see Amazon CloudWatch Pricing. Both methods enable Container Insights on both Linux and Windows worker nodes in the Amazon EKS cluster. To enable Container Insights on Windows, you must use version 1.5.0 or later of the Amazon EKS add-on or the Helm chart. Currently, Application Signals is not supported on Windows in Amazon EKS clusters. The Amazon CloudWatch Observability EKS add-on is supported on Amazon EKS clusters running with Kubernetes version 1.23 or later. When you install the add-on or the Helm chart, you must also grant IAM permissions to enable the CloudWatch agent to send metrics, logs, and traces to CloudWatch. There are two ways to do this: • Attach a policy to the IAM role of your worker nodes. This option grants permissions to worker nodes to send telemetry to CloudWatch. • Use an IAM role for service accounts for the agent pods, and attach the policy to this role. This works only for Amazon EKS clusters. This option gives CloudWatch access only to the appropriate agent pods. Option 1: Install using EKS Pod Identity If you use version 3.1.0 or later of the add-on, you can use EKS Pod Identity to grant the required permissions to the add-on. EKS Pod Identity is the recommended option and provides benefits such as least privilege, credential rotation, and auditability. Additionally, using EKS Pod Identity allows you to install the EKS add-on as part of the cluster creation itself. Option 1: Install using EKS Pod Identity 2706 Amazon CloudWatch User Guide To use this method, first follow the EKS Pod Identity association steps to create the IAM role and set up the EKS Pod Identity agent. Then install the Amazon CloudWatch Observability EKS add-on. To install the add-on, you can use the AWS CLI, the Amazon EKS console, AWS CloudFormation, or Terraform. AWS CLI To use the AWS CLI to install the Amazon CloudWatch Observability EKS add-on Enter the following commands. Replace my-cluster-name with the name of your cluster and replace 111122223333 with your account ID. Replace my-role with the IAM role that you created in the EKS Pod Identity association step. aws iam attach-role-policy \ --role-name my-role \ --policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy aws eks create-addon \ --addon-name amazon-cloudwatch-observability \ --cluster-name my-cluster-name \ --pod-identity-associations serviceAccount=cloudwatch- agent,roleArn=arn:aws:iam::111122223333:role/my-role Amazon EKS console To use the Amazon EKS console to add the Amazon CloudWatch Observability EKS add-on 1. Open the Amazon EKS console at https://console.aws.amazon.com/eks/home#/clusters. 2. In the left navigation pane, choose Clusters. 3. Choose the name of the cluster that you want to configure the Amazon CloudWatch Observability EKS add-on for. 4. Choose the Add-ons tab. 5. Choose Get more add-ons. 6. On the Select add-ons page, do the following: a. In the Amazon EKS-addons section, select the Amazon CloudWatch Observability check box. b. Choose Next. Option 1: Install using EKS Pod Identity 2707 Amazon CloudWatch User Guide 7. On the Configure selected add-ons settings page, do the following: a. b. c. d. Select the Version you'd like to use. For Add-on access, select EKS Pod Identity If you don't have an IAM role configured, choose Create recommended role, then choose Next until you are at Step 3 Name, review, and create. You can change your role name if desired, otherwise, choose Create Role, and then return to the Add-on page and select the IAM role that you just created. (Optional) You can expand the Optional configuration settings. If you select Override for the Conflict resolution method, one or more of the settings for the existing add- on can be overwritten with the Amazon EKS add-on settings. If you don't enable this option and there's a conflict with your existing settings, the operation fails. You can use the resulting error message to troubleshoot the conflict. Before selecting this option, make sure that the Amazon EKS add-on doesn't manage settings that you need to self- manage. e. Choose Next. 8. On the Review and add page, choose Create. After the add-on installation is complete, you see your installed add-on. AWS CloudFormation To use AWS CloudFormation to install the Amazon CloudWatch Observability EKS add-on 1. First, run the following AWS CLI command to attach the necessary IAM policy to your IAM role. Replace my-role with the role that you created in the EKS Pod Identity association step. aws iam attach-role-policy \ --role-name my-role \ --policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy 2. Then create the following resource. Replace my-cluster-name with the name of your cluster, replace 111122223333 with your account ID, and replace my-role with the IAM role created
acw-ug-777
acw-ug.pdf
777
and add page, choose Create. After the add-on installation is complete, you see your installed add-on. AWS CloudFormation To use AWS CloudFormation to install the Amazon CloudWatch Observability EKS add-on 1. First, run the following AWS CLI command to attach the necessary IAM policy to your IAM role. Replace my-role with the role that you created in the EKS Pod Identity association step. aws iam attach-role-policy \ --role-name my-role \ --policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy 2. Then create the following resource. Replace my-cluster-name with the name of your cluster, replace 111122223333 with your account ID, and replace my-role with the IAM role created in EKS Pod Identity association step. For more information, see AWS::EKS::Addon. { Option 1: Install using EKS Pod Identity 2708 Amazon CloudWatch User Guide "Resources": { "EKSAddOn": { "Type": "AWS::EKS::Addon", "Properties": { "AddonName": "amazon-cloudwatch-observability", "ClusterName": "my-cluster-name", "PodIdentityAssociations": [ { "ServiceAccount": "cloudwatch-agent", "RoleArn": "arn:aws:iam::111122223333:role/my-role" } ] } } } } Terraform To use Terraform to install the Amazon CloudWatch Observability EKS add-on 1. Use the following. Replace my-cluster-name with the name of your cluster, replace 111122223333 with your account ID, and replace my-service-account-role with the IAM role created in EKS Pod Identity association step. For more information, see Resource: aws_eks_addon in the Terraform documentation. 2. resource "aws_iam_role_policy_attachment" "CloudWatchAgentServerPolicy" { policy_arn = "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy" role = "my-role" } resource "aws_eks_addon" "example" { cluster_name = "my-cluster-name" addon_name = "amazon-cloudwatch-observability" pod_identity_associations { roleArn = "arn:aws:iam::111122223333:role/my-role" serviceAccount = "cloudwatch-agent" } } Option 1: Install using EKS Pod Identity 2709 Amazon CloudWatch User Guide Option 2: Install with IAM permissions on worker nodes To use this method, first attach the CloudWatchAgentServerPolicy IAM policy to your worker nodes by entering the following command. In this command, replace my-worker-node-role with the IAM role used by your Kubernetes worker nodes. aws iam attach-role-policy \ --role-name my-worker-node-role \ --policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy Then install the Amazon CloudWatch Observability EKS add-on. To install the add-on, you can use the AWS CLI, the console, AWS CloudFormation, or Terraform. AWS CLI To use the AWS CLI to install the Amazon CloudWatch Observability EKS add-on Enter the following command. Replace my-cluster-name with the name of your cluster. aws eks create-addon --addon-name amazon-cloudwatch-observability --cluster-name my- cluster-name Amazon EKS console To use the Amazon EKS console to add the Amazon CloudWatch Observability EKS add-on 1. Open the Amazon EKS console at https://console.aws.amazon.com/eks/home#/clusters. 2. In the left navigation pane, choose Clusters. 3. Choose the name of the cluster that you want to configure the Amazon CloudWatch Observability EKS add-on for. 4. Choose the Add-ons tab. 5. Choose Get more add-ons. 6. On the Select add-ons page, do the following: a. In the Amazon EKS-addons section, select the Amazon CloudWatch Observability check box. b. Choose Next. Option 2: Install with IAM permissions on worker nodes 2710 Amazon CloudWatch User Guide 7. On the Configure selected add-ons settings page, do the following: a. b. Select the Version you'd like to use. (Optional) You can expand the Optional configuration settings. If you select Override for the Conflict resolution method, one or more of the settings for the existing add- on can be overwritten with the Amazon EKS add-on settings. If you don't enable this option and there's a conflict with your existing settings, the operation fails. You can use the resulting error message to troubleshoot the conflict. Before selecting this option, make sure that the Amazon EKS add-on doesn't manage settings that you need to self- manage. c. Choose Next. 8. On the Review and add page, choose Create. After the add-on installation is complete, you see your installed add-on. AWS CloudFormation To use AWS CloudFormation to install the Amazon CloudWatch Observability EKS add-on Replace my-cluster-name with the name of your cluster. For more information, see AWS::EKS::Addon. { "Resources": { "EKSAddOn": { "Type": "AWS::EKS::Addon", "Properties": { "AddonName": "amazon-cloudwatch-observability", "ClusterName": "my-cluster-name" } } } } Helm chart To use the amazon-cloudwatch-observability Helm chart 1. You must have Helm installed to use this chart. For more information about installing Helm, see the Helm documentation. Option 2: Install with IAM permissions on worker nodes 2711 Amazon CloudWatch User Guide 2. After you have installed Helm, enter the following commands. Replace my-cluster-name with the name of your cluster, and replace my-cluster-region with the Region that the cluster runs in. helm repo add aws-observability https://aws-observability.github.io/helm-charts helm repo update aws-observability helm install --wait --create-namespace --namespace amazon-cloudwatch amazon- cloudwatch-observability aws-observability/amazon-cloudwatch-observability --set clusterName=my-cluster-name --set region=my-cluster-region Terraform To use Terraform to install the Amazon CloudWatch Observability EKS add-on Replace my-cluster-name with the name of your cluster. For more information, see Resource: aws_eks_addon. resource "aws_eks_addon" "example" { addon_name = "amazon-cloudwatch-observability" cluster_name = "my-cluster-name" } Option 3: Install using IAM service account role (applies only to using the add-on) This method is valid only if you are using the Amazon CloudWatch Observability EKS add-on. Before using this method, verify the following prerequisites: • You
acw-ug-778
acw-ug.pdf
778
runs in. helm repo add aws-observability https://aws-observability.github.io/helm-charts helm repo update aws-observability helm install --wait --create-namespace --namespace amazon-cloudwatch amazon- cloudwatch-observability aws-observability/amazon-cloudwatch-observability --set clusterName=my-cluster-name --set region=my-cluster-region Terraform To use Terraform to install the Amazon CloudWatch Observability EKS add-on Replace my-cluster-name with the name of your cluster. For more information, see Resource: aws_eks_addon. resource "aws_eks_addon" "example" { addon_name = "amazon-cloudwatch-observability" cluster_name = "my-cluster-name" } Option 3: Install using IAM service account role (applies only to using the add-on) This method is valid only if you are using the Amazon CloudWatch Observability EKS add-on. Before using this method, verify the following prerequisites: • You have a functional Amazon EKS cluster with nodes attached in one of the AWS Regions that supports Container Insights. For the list of supported Regions, see Container Insights. • You have kubectl installed and configured for the cluster. For more information, see Installing kubectl in the Amazon EKS User Guide. • You have eksctl installed. For more information, see Installing or updating eksctl in the Amazon EKS User Guide. Option 3: Install using IAM service account role (applies only to using the add-on) 2712 Amazon CloudWatch AWS CLI User Guide To use the AWS CLI to install the Amazon CloudWatch Observability EKS add-on using the IAM service account role 1. Enter the following command to create an OpenID Connect (OIDC) provider, if the cluster doesn't have one already. For more information, see Configuring a Kubernetes service account to assume an IAM role in the Amazon EKS User Guide. eksctl utils associate-iam-oidc-provider --cluster my-cluster-name --approve 2. Enter the following command to create the IAM role with the CloudWatchAgentServerPolicy policy attached, and configure the agent service account to assume that role using OIDC. Replace my-cluster-name with the name of your cluster, and replace my-service-account-role with the name of the role that you want to associate the service account with. If the role doesn't already exist, eksctl creates it for you. eksctl create iamserviceaccount \ --name cloudwatch-agent \ --namespace amazon-cloudwatch --cluster my-cluster-name \ --role-name my-service-account-role \ --attach-policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy \ --role-only \ --approve 3. Install the add-on by entering the following command. Replace my-cluster-name with the name of your cluster, replace 111122223333 with your account ID, and replace my- service-account-role with the IAM role created in the previous step. aws eks create-addon --addon-name amazon-cloudwatch-observability --cluster-name my-cluster-name --service-account-role-arn arn:aws:iam::111122223333:role/my-service-account-role Option 3: Install using IAM service account role (applies only to using the add-on) 2713 Amazon CloudWatch Amazon EKS console User Guide To use the console to install the Amazon CloudWatch Observability EKS add-on using the IAM service account role 1. Open the Amazon EKS console at https://console.aws.amazon.com/eks/home#/clusters. 2. In the left navigation pane, choose Clusters. 3. Choose the name of the cluster that you want to configure the Amazon CloudWatch Observability EKS add-on for. 4. Choose the Add-ons tab. 5. Choose Get more add-ons. 6. On the Select add-ons page, do the following: a. In the Amazon EKS-addons section, select the Amazon CloudWatch Observability check box. b. Choose Next. 7. On the Configure selected add-ons settings page, do the following: a. b. c. d. Select the Version you'd like to use. For Add-on access, select IAM roles for service accounts (IRSA) Select the IAM role in the Add-on access box. (Optional) You can expand the Optional configuration settings. If you select Override for the Conflict resolution method, one or more of the settings for the existing add- on can be overwritten with the Amazon EKS add-on settings. If you don't enable this option and there's a conflict with your existing settings, the operation fails. You can use the resulting error message to troubleshoot the conflict. Before selecting this option, make sure that the Amazon EKS add-on doesn't manage settings that you need to self- manage. e. Choose Next. 8. On the Review and add page, choose Create. After the add-on installation is complete, you see your installed add-on. Option 3: Install using IAM service account role (applies only to using the add-on) 2714 Amazon CloudWatch User Guide Considerations for Amazon EKS Hybrid Nodes Node-level metrics aren't available for hybrid nodes because Container Insights depends on the availability of the EC2 Instance Metadata Service (IMDS) for node-level metrics. Cluster, workload, Pod, and container-level metrics are available for hybrid nodes. After you install the add-on by following the steps in the previous sections, you must update the add-on manifest so that the agent can run successfully on hybrid nodes. Edit the amazoncloudwatchagents resource in the cluster to add the RUN_WITH_IRSA environment variable to match the following. kubectl edit amazoncloudwatchagents -n amazon-cloudwatch cloudwatch-agent apiVersion: v1 items: - apiVersion: cloudwatch.aws.amazon.com/v1alpha1 kind: AmazonCloudWatchAgent metadata: ... name: cloudwatch-agent namespace: amazon-cloudwatch ... spec: ... env: - name: RUN_WITH_IRSA # <-- Add this value: "True" # <-- Add this - name: K8S_NODE_NAME valueFrom: fieldRef: fieldPath: spec.nodeName ... (Optional) Additional configuration Topics • Opt
acw-ug-779
acw-ug.pdf
779
for hybrid nodes. After you install the add-on by following the steps in the previous sections, you must update the add-on manifest so that the agent can run successfully on hybrid nodes. Edit the amazoncloudwatchagents resource in the cluster to add the RUN_WITH_IRSA environment variable to match the following. kubectl edit amazoncloudwatchagents -n amazon-cloudwatch cloudwatch-agent apiVersion: v1 items: - apiVersion: cloudwatch.aws.amazon.com/v1alpha1 kind: AmazonCloudWatchAgent metadata: ... name: cloudwatch-agent namespace: amazon-cloudwatch ... spec: ... env: - name: RUN_WITH_IRSA # <-- Add this value: "True" # <-- Add this - name: K8S_NODE_NAME valueFrom: fieldRef: fieldPath: spec.nodeName ... (Optional) Additional configuration Topics • Opt out of collecting container logs • Use a custom Fluent Bit configuration • Manage Kubernetes tolerations for the installed pod workloads Considerations for Amazon EKS Hybrid Nodes 2715 Amazon CloudWatch User Guide • Opt out of accelerated compute metrics collection • Use a custom CloudWatch agent configuration • Manage admission webhook TLS certificates • Collect Amazon EBS volume IDs Opt out of collecting container logs By default, the add-on uses Fluent Bit to collect container logs from all pods and then sends the logs to CloudWatch Logs. For information about which logs are collected, see Setting up Fluent Bit. Note Neither the add-on or the Helm chart manage existing Fluentd or Fluent Bit resources in a cluster. You can delete the existing Fluentd or Fluent Bit resources before installing the add-on or Helm chart. Alternatively, to keep your existing setup and avoid having the add- on or the Helm chart from also installing Fluent Bit, you can disable it by following the instructions in this section. To opt out of the collection of container logs if you are using the Amazon CloudWatch Observability EKS add-on, pass the following option when you create or update the add-on: --configuration-values '{ "containerLogs": { "enabled": false } }' To opt out of the collection of container logs if you are using the Helm chart, pass the following option when you create or update the add-on: --set containerLogs.enabled=false Use a custom Fluent Bit configuration Starting with version 1.7.0 of the Amazon CloudWatch Observability EKS add-on, you can modify the Fluent Bit configuration when you create or update the add-on or Helm chart. You supply the custom Fluent Bit configuration in the containerLogs root level section of the advanced configuration of the add-on or the value overrides in the Helm chart. Within this section, you supply the custom Fluent Bit configuration in the config section (for Linux) or configWindows section (for Windows). The config is further broken down into the following sub-sections: (Optional) Additional configuration 2716 Amazon CloudWatch User Guide • service– This section represents the SERVICE config to define the global behavior of the Fluent Bit engine. • customParsers– This section represents any global PARSERs that you want to include that are capable of taking unstructured log entries and giving them a structure to make it easier for processing and further filtering. • extraFiles– This section can be used to provide additional Fluent Bit conf files to be included. By default, the following 3 conf files are included:. • application-log.conf– A conf file for sending application logs from your cluster to the log group /aws/containerinsights/my-cluster-name/application in CloudWatch Logs. • dataplane-log.conf– A conf file for sending logs corresponding to your cluster’s data plane components including the CRI logs, kubelet logs, kube-proxy logs and Amazon VPC CNI logs to the log group /aws/containerinsights/my-cluster-name/dataplane in CloudWatch Logs. • host-log.conf– A conf for sending logs from /var/log/dmesg, /var/log/messages, and /var/log/secure on Linux, and System winlogs on Windows, to the log group /aws/ containerinsights/my-cluster-name/host in CloudWatch. Note Provide the full configuration for each of these individual sections even if you are modifying only one field within a sub-section. We recommend that you use the default configuration provided below as a baseline and then modify it accordingly so that you don't disable functionality that is enabled by default. You can use the following YAML configuration when modifying the advanced config for the Amazon EKS add-on or when you supply value overrides for the Helm chart. To find the config section for your cluster, see aws-observability / helm-charts on GitHub and find the release corresponding to the version of the add-on or Helm chart that you are installing. Then navigate to /charts/amazon-cloudwatch-observability/values.yaml to find the config section (for Linux) and configWindows section (for Windows) within the fluentBit section under containerLogs. As an example, the default Fluent Bit configuration for version 1.7.0 can be found here. (Optional) Additional configuration 2717 Amazon CloudWatch User Guide We recommend that you provide the config as YAML when you supply it using the Amazon EKS add-on’s advanced config or when you supply it as value overrides for your Helm installation. Be sure that the YAML conforms to the following structure. containerLogs: fluentBit: config: service: | ... customParsers:
acw-ug-780
acw-ug.pdf
780
Helm chart that you are installing. Then navigate to /charts/amazon-cloudwatch-observability/values.yaml to find the config section (for Linux) and configWindows section (for Windows) within the fluentBit section under containerLogs. As an example, the default Fluent Bit configuration for version 1.7.0 can be found here. (Optional) Additional configuration 2717 Amazon CloudWatch User Guide We recommend that you provide the config as YAML when you supply it using the Amazon EKS add-on’s advanced config or when you supply it as value overrides for your Helm installation. Be sure that the YAML conforms to the following structure. containerLogs: fluentBit: config: service: | ... customParsers: | ... extraFiles: application-log.conf: | ... dataplane-log.conf: | ... host-log.conf: | ... The following example config changes the global setting for the flush interval to be 45 seconds. Even though the only modification is to the Flush field, you must still provide the full SERVICE definition for the service sub-section. Because this example didn't specify overrides for the other sub-sections, the defaults are used for them. containerLogs: fluentBit: config: service: | [SERVICE] Flush 45 Grace 30 Log_Level error Daemon off Parsers_File parsers.conf storage.path /var/fluent-bit/state/flb-storage/ storage.sync normal storage.checksum off storage.backlog.mem_limit 5M (Optional) Additional configuration 2718 Amazon CloudWatch User Guide The following example configuration includes an extra Fluent bit conf file. In this example, we are adding a custom my-service.conf under extraFiles and it will be included in addition to the three default extraFiles. containerLogs: fluentBit: config: extraFiles: my-service.conf: | [INPUT] Name tail Tag myservice.* Path /var/log/containers/*myservice*.log DB /var/fluent-bit/state/flb_myservice.db Mem_Buf_Limit 5MB Skip_Long_Lines On Ignore_Older 1d Refresh_Interval 10 [OUTPUT] Name cloudwatch_logs Match myservice.* region ${AWS_REGION} log_group_name /aws/containerinsights/${CLUSTER_NAME}/myservice log_stream_prefix ${HOST_NAME}- auto_create_group true The next example removes an existing conf file entirely from extraFiles. This excludes the application-log.conf entirely by overriding it with an empty string. Simply omitting application-log.conf from extraFiles would instead imply to use the default, which is not what we are trying to achieve in this example. The same applies to removing any custom conf file that you might have previously added to extraFiles. containerLogs: fluentBit: config: extraFiles: application-log.conf: "" (Optional) Additional configuration 2719 Amazon CloudWatch User Guide Manage Kubernetes tolerations for the installed pod workloads Starting with version 1.7.0 of the Amazon CloudWatch Observability EKS add-on, the add-on and the Helm chart by default set Kubernetes tolerations to tolerate all taints on the pod workloads that are installed by the add-on or the Helm chart. This ensures that daemonsets such as the CloudWatch agent and Fluent Bit can schedule pods on all nodes in your cluster by default. For more information about tolerations and taints, see Taints and Tolerations in the Kubernetes documentation. The default tolerations set by the add-on or the Helm chart are as follows: tolerations: - operator: Exists You can override the default tolerations by setting the tolerations field at the root level when using the add-on advanced config or when you install or upgrade the Helm chart with value overrides. An example would look like the following: tolerations: - key: "key1" operator: "Exists" effect: "NoSchedule" To omit tolerations completely, you can use a config that looks like the following: tolerations: [] Any changes to tolerations apply to all pod workloads that are installed by the add-on or the Helm chart. Opt out of accelerated compute metrics collection By default, Container Insights with enhanced observability collects metrics for Accelerated Compute monitoring, including NVIDIA GPU metrics, AWS Neuron metrics for AWS Trainium and AWS Inferentia, and AWS Elastic Fabric Adapter (EFA) metrics. NVIDIA GPU metrics from Amazon EKS workloads are collected by default beginning with version v1.3.0-eksbuild.1 of the EKS add-on or the Helm chart and version 1.300034.0 of the CloudWatch agent. For a list of metrics collected and prerequisites, see NVIDIA GPU metrics. (Optional) Additional configuration 2720 Amazon CloudWatch User Guide AWS Neuron metrics for AWS Trainium and AWS Inferentia accelerators are collected by default beginning with version v1.5.0-eksbuild.1 of the EKS add-on or the Helm chart, and version 1.300036.0 of the CloudWatch agent. For a list of metrics collected and prerequisites, see AWS Neuron metrics for AWS Trainium and AWS Inferentia . AWS Elastic Fabric Adapter (EFA) metrics from Linux nodes on Amazon EKS clusters are collected by default beginning with version v1.5.2-eksbuild.1 of the EKS add-on or the Helm chart and version 1.300037.0 of the CloudWatch agent. For a list of metrics collected and prerequisites, see AWS Elastic Fabric Adapter (EFA) metrics . You can opt out of collecting these metrics by setting the accelerated_compute_metrics field in the CloudWatch agent configuration file to false. This field is in the kubernetes section of the metrics_collected section in the CloudWatch configuration file. The following is an example of an opt-out configuration. For more information about how to use custom CloudWatch agent configurations, see the following section, Use a custom CloudWatch agent configuration. { "logs": { "metrics_collected": { "kubernetes":
acw-ug-781
acw-ug.pdf
781
or the Helm chart and version 1.300037.0 of the CloudWatch agent. For a list of metrics collected and prerequisites, see AWS Elastic Fabric Adapter (EFA) metrics . You can opt out of collecting these metrics by setting the accelerated_compute_metrics field in the CloudWatch agent configuration file to false. This field is in the kubernetes section of the metrics_collected section in the CloudWatch configuration file. The following is an example of an opt-out configuration. For more information about how to use custom CloudWatch agent configurations, see the following section, Use a custom CloudWatch agent configuration. { "logs": { "metrics_collected": { "kubernetes": { "enhanced_container_insights": true, "accelerated_compute_metrics": false } } } } Use a custom CloudWatch agent configuration To collect other metrics, logs or traces using the CloudWatch agent, you can specify a custom configuration while also keeping Container Insights and CloudWatch Application Signals enabled. To do so, embed the CloudWatch agent configuration file within the config key under the agent key of the advanced configuration that you can use when creating or updating the EKS add-on or the Helm chart. The following represents the default agent configuration when you do not provide any additional configuration. Important Any custom configuration that you provide using additional configuration settings overrides the default configuration used by the agent. Be cautious not to unintentionally (Optional) Additional configuration 2721 Amazon CloudWatch User Guide disable functionality that is enabled by default, such as Container Insights with enhanced observability and CloudWatch Application Signals. In the scenario that you are required to provide a custom agent configuration, we recommend using the following default configuration as a baseline and then modifying it accordingly. • For using the Amazon CloudWatch observability EKS add-on --configuration-values '{ "agent": { "config": { "logs": { "metrics_collected": { "application_signals": {}, "kubernetes": { "enhanced_container_insights": true } } }, "traces": { "traces_collected": { "application_signals": {} } } } }' • For using the Helm chart --set agent.config='{ "logs": { "metrics_collected": { "application_signals": {}, "kubernetes": { "enhanced_container_insights": true } } }, "traces": { "traces_collected": { "application_signals": {} (Optional) Additional configuration 2722 Amazon CloudWatch } } }' User Guide The following example shows the default agent configuration for the CloudWatch agent on Windows. The CloudWatch agent on Windows does not support custom configuration. { "logs": { "metrics_collected": { "kubernetes": { "enhanced_container_insights": true }, } } } Manage admission webhook TLS certificates The Amazon CloudWatch Observability EKS add-on and the Helm chart leverage Kubernetes admission webhooks to validate and mutate AmazonCloudWatchAgent and Instrumentation custom resource (CR) requests, and optionally Kubernetes pod requests on the cluster if CloudWatch Application Signals is enabled. In Kubernetes, webhooks require a TLS certificate that the API server is configured to trust in order to ensure secure communication. By default, the Amazon CloudWatch Observability EKS add-on and the Helm chart auto-generate a self-signed CA and a TLS certificate signed by this CA for securing the communication between the API server and the webhook server. This auto-generated certificate has a default expiry of 10 years and is not auto-renewed upon expiry. In addition, the CA bundle and the certificate are re-generated every time the add-on or Helm chart is upgraded or re-installed, thus resetting the expiry. If you want to change the default expiry of the auto-generated certificate, you can use the following additional configurations when creating or updating the add-on. Replace expiry-in- days with your desired expiry duration in days. • Use this for the Amazon CloudWatch Observability EKS add-on --configuration-values '{ "admissionWebhooks": { "autoGenerateCert": { "expiryDays": expiry-in-days } } }' • Use this for the Helm chart (Optional) Additional configuration 2723 Amazon CloudWatch User Guide --set admissionWebhooks.autoGenerateCert.expiryDays=expiry-in-days For a more secure and feature-rich certificate authority solution, the add-on has opt-in support for cert-manager, a widely-adopted solution for TLS certificate management in Kubernetes that simplifies the process of obtaining, renewing, managing and using those certificates. It ensures that certificates are valid and up to date, and attempts to renew certificates at a configured time before expiry. cert-manager also facilitates issuing certificates from a variety of supported sources, including AWS Certificate Manager Private Certificate Authority. We recommend that you review best practices for management of TLS certificates on your clusters and advise you to opt in to cert-manager for production environments. Note that if you opt-in to enabling cert-manager for managing the admission webhook TLS certificates, you are required to pre-install cert-manager on your Amazon EKS cluster before you install the Amazon CloudWatch Observability EKS add-on or the Helm chart. For more information about available installation options, see cert-manager documentation. After you install it, you can opt in to using cert- manager for managing the admission webhook TLS certificates using the following additional configuration. • If you are using the Amazon CloudWatch Observability EKS add-on --configuration-values '{ "admissionWebhooks": { "certManager": { "enabled": true } } }' • If you are
acw-ug-782
acw-ug.pdf
782
environments. Note that if you opt-in to enabling cert-manager for managing the admission webhook TLS certificates, you are required to pre-install cert-manager on your Amazon EKS cluster before you install the Amazon CloudWatch Observability EKS add-on or the Helm chart. For more information about available installation options, see cert-manager documentation. After you install it, you can opt in to using cert- manager for managing the admission webhook TLS certificates using the following additional configuration. • If you are using the Amazon CloudWatch Observability EKS add-on --configuration-values '{ "admissionWebhooks": { "certManager": { "enabled": true } } }' • If you are using the Helm chart --set admissionWebhooks.certManager.enabled=true --configuration-values '{ "admissionWebhooks": { "certManager": { "enabled": true } } }' The advanced configuration discussed in this section will by default use a SelfSigned issuer. Collect Amazon EBS volume IDs If you want to collect Amazon EBS volume IDs in the performance logs, you must add another policy to the IAM role that is attached to the worker nodes or to the service account. Add the (Optional) Additional configuration 2724 Amazon CloudWatch User Guide following as an inline policy. For more information, see Adding and Removing IAM Identity Permissions. { "Version": "2012-10-17", "Statement": [ { "Action": [ "ec2:DescribeVolumes" ], "Resource": "*", "Effect": "Allow" } ] } Troubleshooting the Amazon CloudWatch Observability EKS add-on or the Helm chart Use the following information to help troubleshoot problems with the Amazon CloudWatch Observability EKS add-on or the Helm chart Topics • Updating and deleting the Amazon CloudWatch Observability EKS add-on or the Helm chart • Verify the version of the CloudWatch agent used by the Amazon CloudWatch Observability EKS add-on or the Helm chart • Handling a ConfigurationConflict when managing the add-on or the Helm chart Updating and deleting the Amazon CloudWatch Observability EKS add-on or the Helm chart For instructions about updating or deleting the Amazon CloudWatch Observability EKS add-on, see Managing Amazon EKS add-ons. Use amazon-cloudwatch-observability as the name of the add-on. To delete the Helm chart in a cluster, enter the following command. Troubleshooting 2725 Amazon CloudWatch User Guide helm delete amazon-cloudwatch-observability -n amazon-cloudwatch --wait Verify the version of the CloudWatch agent used by the Amazon CloudWatch Observability EKS add-on or the Helm chart The Amazon CloudWatch Observability EKS add-on and the Helm chart installs a custom resource of kind AmazonCloudWatchAgent that controls the behavior of the CloudWatch agent daemonset on the cluster, including the version of the CloudWatch agent being used. You can get a list of all the AmazonCloudWatchAgent custom resources installed on your cluster u by entering the following command: kubectl get amazoncloudwatchagent -A In the output of this command, you should be able to check the version of the CloudWatch agent. Alternatively, you can also describe the amazoncloudwatchagent resource or one of the cloudwatch-agent-* pods running on your cluster to inspect the image being used. Handling a ConfigurationConflict when managing the add-on or the Helm chart When you install or update the Amazon CloudWatch Observability EKS add-on or the Helm chart, if you notice a failure caused by existing resources, it is likely because you already have the CloudWatch agent and its associated components such as the ServiceAccount, the ClusterRole and the ClusterRoleBinding installed on the cluster. The error displayed by the add-on will include Conflicts found when trying to apply. Will not continue due to resolve conflicts mode, The error displayed by the Helm chart will be similar to Error: INSTALLATION FAILED: Unable to continue with install and invalid ownership metadata.. When the add-on or the Helm chart tries to install the CloudWatch agent and its associated components, if it detects any change in the contents, it by default fails the installation or update to avoid overwriting the state of the resources on the cluster. If you are trying to onboard to the Amazon CloudWatch Observability EKS add-on and you see this failure, we recommend deleting an existing CloudWatch agent setup that you had previously installed on the cluster and then installing the EKS add-on or Helm chart. Be sure to back up any customizations you might have made to the original CloudWatch agent setup such as a custom agent configuration, and provide these to the add-on or Helm chart when you next install or Troubleshooting 2726 Amazon CloudWatch User Guide update it. If you had previously installed the CloudWatch agent for onboarding to Container Insights, see Deleting the CloudWatch agent and Fluent Bit for Container Insights for more information. Alternatively, the add-on supports a conflict resolution configuration option that has the capability to specify OVERWRITE. You can use this option to proceed with installing or updating the add-on by overwriting the conflicts on the cluster. If you are using the Amazon EKS console, you'll find the Conflict resolution method when you choose the Optional configuration settings when you
acw-ug-783
acw-ug.pdf
783
chart when you next install or Troubleshooting 2726 Amazon CloudWatch User Guide update it. If you had previously installed the CloudWatch agent for onboarding to Container Insights, see Deleting the CloudWatch agent and Fluent Bit for Container Insights for more information. Alternatively, the add-on supports a conflict resolution configuration option that has the capability to specify OVERWRITE. You can use this option to proceed with installing or updating the add-on by overwriting the conflicts on the cluster. If you are using the Amazon EKS console, you'll find the Conflict resolution method when you choose the Optional configuration settings when you create or update the add-on. If you are using the AWS CLI, you can supply the --resolve- conflicts OVERWRITE to your command to create or update the add-on. Collect Java Management Extensions (JMX) metrics The CloudWatch agent supports Java Management Extensions (JMX) metrics collection on Amazon EKS. This allows you to collect additional metrics from Java applications running on Amazon EKS clusters enabling insight into performance, memory usage, traffic, and other critical metrics. For more information, see Collect Java Management Extensions (JMX) metrics. Enable Kueue metrics Beginning with version v2.4.0-eksbuild.1 of the the CloudWatch Observability EKS add-on, Container Insights for Amazon EKS supports collecting Kueue metrics from Amazon EKS clusters. For more information about these metrics, see Kueue metrics . If you are using the Amazon SageMaker AI Hyperpod Task Governance EKS add-on, you can skip the steps in the Prerequisites section and just follow the steps in Enable the configuration flag. Prerequisites Before you install Kueue in your Amazon EKS cluster, make the following updates in the manifest file: 1. Enable the optional cluster queue resource metrics for Kueue. To do this, modify the in-line controller_manager_config.yaml in the kueue-system ConfigMap. In the metrics section, add or uncomment the line enableClusterQueueResources: true. apiVersion: v1 data: controller_manager_config.yaml: | apiVersion: config.kueue.x-k8s.io/v1beta1 Collect Java Management Extensions (JMX) metrics 2727 Amazon CloudWatch User Guide kind: Configuration health: healthProbeBindAddress: :8081 metrics: bindAddress: :8080 enableClusterQueueResources: true <-- ADD/UNCOMMENT THIS LINE 2. By default, all k8s services are available cluster-wide. Kueue creates a service kueue- controller-manager-metrics-service for exposing metrics. To prevent duplicate observations for metrics, modify this service to allow access only to the metrics service from the same node. To do this, add the line internalTrafficPolicy: Local to the kueue- controller-manager-metrics-service definition. apiVersion: v1 kind: Service metadata: labels: ... name: kueue-controller-manager-metrics-service namespace: kueue-system spec: ports: - name: https port: 8443 protocol: TCP targetPort: https internalTrafficPolicy: Local <-- ADD THIS LINE selector: control-plane: controller-manager 3. Lastly, the kueue-controller-manager pod creates a kube-rbac-proxy container. This container currently has a high level of logging verbosity, which causes the cluster's bearer token to be logged by that container when the metrics scraper accesses the kueue-controller- manager-metrics-service. We recommend that you decrease this logging verbosity. The default value in the manifest distributed by Kueue is 10, we recommend to change it to 0. apiVersion: apps/v1 kind: Deployment metadata: labels: ... name: kueue-controller-manager Enable Kueue metrics 2728 User Guide Amazon CloudWatch namespace: kueue-system spec: ... template: ... spec: containers: ... - args: - --secure-listen-address=0.0.0.0:8443 - --upstream=http://127.0.0.1:8080/ - --logtostderr=true - --v=0 <-- CHANGE v=10 TO v=0 image: gcr.io/kubebuilder/kube-rbac-proxy:v0.8.0 name: kube-rbac-proxy ... Enable the configuration flag To enable the Kueue metrics, you must enable kueue_container_insights in the add- on additional configuration. You can do this either by using the AWS CLI to set up the EKS Observability add-on, or by using the Amazon EKS console. After you have successfully installed the EKS Observability add-on with one of the following methods, you can view your Amazon EKS cluster metrics under the HyperPod console Dashboard tab. AWS CLI To enable Kueue metrics using the AWS CLI • Enter the following AWS CLI command to install the add-on. aws eks create-addon --cluster-name cluster-name --addon-name amazon-cloudwatch- observability --configuration-values "configuration_json_file" The following is an example of the JSON file with the configuration values. { "agent": { "config": { Enable Kueue metrics 2729 Amazon CloudWatch User Guide "logs": { "metrics_collected": { "kubernetes": { "kueue_container_insights": true, "enhanced_container_insights": true }, "application_signals": { } } }, "traces": { "traces_collected": { "application_signals": { } } } }, }, } Amazon EKS console To enable Kueue metrics using the Amazon EKS console 1. Open the Amazon EKS console at https://console.aws.amazon.com/eks/home#/clusters. 2. Choose the name of your cluster. 3. Choose Add-ons. 4. Find the Amazon CloudWatch Observability add-on in the list, and install it. When you do so, choose Optional configuration and include the following JSON configuration values. { "agent": { "config": { "logs": { "metrics_collected": { "kubernetes": { "kueue_container_insights": true, "enhanced_container_insights": true }, "application_signals": { } } }, "traces": { Enable Kueue metrics 2730 Amazon CloudWatch User Guide "traces_collected": { "application_signals": { } } } }, }, } Appending OpenTelemetry collector configuration files The CloudWatch agent supports supplemental OpenTelemetry collector configuration files alongside its own
acw-ug-784
acw-ug.pdf
784
Amazon EKS console at https://console.aws.amazon.com/eks/home#/clusters. 2. Choose the name of your cluster. 3. Choose Add-ons. 4. Find the Amazon CloudWatch Observability add-on in the list, and install it. When you do so, choose Optional configuration and include the following JSON configuration values. { "agent": { "config": { "logs": { "metrics_collected": { "kubernetes": { "kueue_container_insights": true, "enhanced_container_insights": true }, "application_signals": { } } }, "traces": { Enable Kueue metrics 2730 Amazon CloudWatch User Guide "traces_collected": { "application_signals": { } } } }, }, } Appending OpenTelemetry collector configuration files The CloudWatch agent supports supplemental OpenTelemetry collector configuration files alongside its own configuration files. This feature allows you to use CloudWatch agent features such as CloudWatch Application Signals or Container Insights through the CloudWatch agent configuration and bring in your existing OpenTelemetry collector configuration with a single agent. To prevent merge conflicts with pipelines automatically created by CloudWatch agent, we recommend that you add a custom suffix to each of the components and pipelines in your OpenTelemetry collector configuration. This will prevent clashing and merge conflicts. • If you are using the Amazon CloudWatch Observability EKS add-on --configuration-values file://values.yaml or --configuration-values ' agent: otelConfig: receivers: otlp/custom-suffix: protocols: http: {} exporters: awscloudwatchlogs/custom-suffix: log_group_name: "test-group" log_stream_name: "test-stream" service: pipelines: logs/custom-suffix: receivers: [otlp/custom-suffix] Appending OpenTelemetry collector configuration files 2731 Amazon CloudWatch User Guide exporters: [awscloudwatchlogs/custom-suffix] ' • If you are using the Helm chart --set agent.otelConfig=' receivers: otlp/custom-suffix: protocols: http: {} exporters: awscloudwatchlogs/custom-suffix: log_group_name: "test-group" log_stream_name: "test-stream" service: pipelines: logs/custom-suffix: receivers: [otlp/custom-suffix] exporters: [awscloudwatchlogs/custom-suffix] ' Metrics collected by the CloudWatch agent You can collect metrics from servers by installing the CloudWatch agent on the server. You can install the agent on both Amazon EC2 instances and on-premises servers. You can also install the agent on computers running Linux, Windows Server, or macOS. If you install the agent on an Amazon EC2 instance, the metrics the agent collects are in addition to the metrics enabled by default on Amazon EC2 instances. For information about installing the CloudWatch agent on an instance, see Collect metrics, logs, and traces with the CloudWatch agent. You can use this section to learn about metrics the CloudWatch agent collects. Metrics collected by the CloudWatch agent on Windows Server instances On a server running Windows Server, installing the CloudWatch agent enables you to collect the metrics associated with the counters in Windows Performance Monitor. The CloudWatch metric names for these counters are created by putting a space between the object name and the counter name. For example, the % Interrupt Time counter of the Processor object is given the metric Metrics collected by the CloudWatch agent 2732 Amazon CloudWatch User Guide name Processor % Interrupt Time in CloudWatch. For more information about Windows Performance Monitor counters, see the Microsoft Windows Server documentation. The default namespace for metrics collected by the CloudWatch agent is CWAgent, although you can specify a different namespace when you configure the agent. Metrics collected by the CloudWatch agent on Linux and macOS instances The following table lists the metrics that you can collect with the CloudWatch agent on Linux servers and macOS computers. Metric Description cpu_time_active The amount of time that the CPU is active in any capacity. This metric is measured in hundredths of a cpu_time_guest cpu_time_guest_nice second. Unit: None The amount of time that the CPU is running a virtual CPU for a guest operating system. This metric is measured in hundredths of a second. Unit: None The amount of time that the CPU is running a virtual CPU for a guest operating system, which is low-priority and can be interrupted by other processes. This metric is measured in hundredths of a second. Unit: None cpu_time_idle The amount of time that the CPU is idle. This metric is measured in hundredths of a second. Unit: None Metrics collected by the CloudWatch agent on Linux and macOS instances 2733 Amazon CloudWatch Metric cpu_time_iowait User Guide Description The amount of time that the CPU is waiting for I/O operations to complete. This metric is measured in hundredths of a second. Unit: None cpu_time_irq The amount of time that the CPU is servicing interrupts. This metric is measured in hundredths of cpu_time_nice cpu_time_softirq cpu_time_steal cpu_time_system a second. Unit: None The amount of time that the CPU is in user mode with low-priority processes, which can easily be interrupted by higher-priority processes. This metric is measured in hundredths of a second. Unit: None The amount of time that the CPU is servicing software interrupts. This metric is measured in hundredths of a second. Unit: None The amount of time that the CPU is in stolen time, which is time spent in other operating systems in a virtualized environment. This metric is measured in hundredths of a second. Unit: None The amount of time that the CPU is in system mode.
acw-ug-785
acw-ug.pdf
785
The amount of time that the CPU is in user mode with low-priority processes, which can easily be interrupted by higher-priority processes. This metric is measured in hundredths of a second. Unit: None The amount of time that the CPU is servicing software interrupts. This metric is measured in hundredths of a second. Unit: None The amount of time that the CPU is in stolen time, which is time spent in other operating systems in a virtualized environment. This metric is measured in hundredths of a second. Unit: None The amount of time that the CPU is in system mode. This metric is measured in hundredths of a second. Unit: None Metrics collected by the CloudWatch agent on Linux and macOS instances 2734 Amazon CloudWatch Metric cpu_time_user User Guide Description The amount of time that the CPU is in user mode. This metric is measured in hundredths of a second. Unit: None cpu_usage_active The percentage of time that the CPU is active in any capacity. cpu_usage_guest The percentage of time that the CPU is running a virtual CPU for a guest operating system. Unit: Percent cpu_usage_guest_nice Unit: Percent The percentage of time that the CPU is running a virtual CPU for a guest operating system, which is low-priority and can be interrupted by other processes. Unit: Percent cpu_usage_idle The percentage of time that the CPU is idle. Unit: Percent cpu_usage_iowait The percentage of time that the CPU is waiting for I/O operations to complete. Unit: Percent cpu_usage_irq The percentage of time that the CPU is servicing interrupts. Unit: Percent Metrics collected by the CloudWatch agent on Linux and macOS instances 2735 Amazon CloudWatch Metric cpu_usage_nice User Guide Description The percentage of time that the CPU is in user mode with low-priority processes, which higher-pr iority processes can easily interrupt. Unit: Percent cpu_usage_softirq The percentage of time that the CPU is servicing software interrupts. Unit: Percent cpu_usage_steal The percentage of time that the CPU is in stolen time, or time spent in other operating systems in a virtualized environment. Unit: Percent cpu_usage_system The percentage of time that the CPU is in system mode. cpu_usage_user The percentage of time that the CPU is in user mode. Unit: Percent Unit: Percent disk_free Free space on the disks. Unit: Bytes disk_inodes_free The number of available index nodes on the disk. Unit: Count disk_inodes_total The total number of index nodes reserved on the disk. Unit: Count Metrics collected by the CloudWatch agent on Linux and macOS instances 2736 Amazon CloudWatch Metric Description User Guide disk_inodes_used The number of used index nodes on the disk. disk_total Total space on the disks, including used and free. Unit: Count Unit: Bytes disk_used Used space on the disks. Unit: Bytes disk_used_percent The percentage of total disk space that is used. Unit: Percent diskio_iops_in_progress The number of I/O requests that have been issued to the device driver but have not yet completed. diskio_io_time The amount of time that the disk has had I/O requests queued. Unit: Count Unit: Milliseconds The only statistic that should be used for this metric is Sum. Do not use Average. diskio_reads The number of disk read operations. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. Metrics collected by the CloudWatch agent on Linux and macOS instances 2737 Amazon CloudWatch Metric Description User Guide diskio_read_bytes The number of bytes read from the disks. diskio_read_time Unit: Bytes The only statistic that should be used for this metric is Sum. Do not use Average. The amount of time that read requests have waited on the disks. Multiple read requests waiting at the same time increase the number. For example, if 5 requests all wait for an average of 100 milliseconds, 500 is reported. Unit: Milliseconds The only statistic that should be used for this metric is Sum. Do not use Average. diskio_writes The number disk write operations. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. diskio_write_bytes The number of bytes written to the disks. Unit: Bytes The only statistic that should be used for this metric is Sum. Do not use Average. Metrics collected by the CloudWatch agent on Linux and macOS instances 2738 Amazon CloudWatch Metric diskio_write_time User Guide Description The amount of time that write requests have waited on the disks. Multiple write requests waiting at the same time increase the number. For example, if 8 requests all wait for an average of 1000 milliseco nds, 8000 is reported. Unit: Milliseconds The only statistic that should be used for this metric is Sum. Do not use Average. ethtool_bw_in_allowance_exc eeded The number of packets queued and/or dropped because the inbound aggregate bandwidth exceeded the maximum for the instance. This metric is collected only if you have listed
acw-ug-786
acw-ug.pdf
786
on Linux and macOS instances 2738 Amazon CloudWatch Metric diskio_write_time User Guide Description The amount of time that write requests have waited on the disks. Multiple write requests waiting at the same time increase the number. For example, if 8 requests all wait for an average of 1000 milliseco nds, 8000 is reported. Unit: Milliseconds The only statistic that should be used for this metric is Sum. Do not use Average. ethtool_bw_in_allowance_exc eeded The number of packets queued and/or dropped because the inbound aggregate bandwidth exceeded the maximum for the instance. This metric is collected only if you have listed it in the ethtool subsection of the metrics_c ollected section of the CloudWatch agent configuration file. For more information, see Collect network performance metrics Unit: None ethtool_bw_out_allowance_ex ceeded The number of packets queued and/or dropped because the outbound aggregate bandwidth exceeded the maximum for the instance. This metric is collected only if you have listed it in the ethtool subsection of the metrics_c ollected section of the CloudWatch agent configuration file. For more information, see Collect network performance metrics Unit: None Metrics collected by the CloudWatch agent on Linux and macOS instances 2739 Amazon CloudWatch Metric ethtool_conntrack_allowance _exceeded ethtool_linklocal_allowance _exceeded User Guide Description The number of packets dropped because connectio n tracking exceeded the maximum for the instance and new connections could not be established. This can result in packet loss for traffic to or from the instance. This metric is collected only if you have listed it in the ethtool subsection of the metrics_c ollected section of the CloudWatch agent configuration file. For more information, see Collect network performance metrics Unit: None The number of packets dropped because the PPS of the traffic to local proxy services exceeded the maximum for the network interface. This impacts traffic to the DNS service, the Instance Metadata Service, and the Amazon Time Sync Service. This metric is collected only if you have listed it in the ethtool subsection of the metrics_c ollected section of the CloudWatch agent configuration file. For more information, see Collect network performance metrics Unit: None Metrics collected by the CloudWatch agent on Linux and macOS instances 2740 Amazon CloudWatch Metric Description User Guide ethtool_pps_allowance_excee ded The number of packets queued and/or dropped because the bidirectional PPS exceeded the maximum for the instance. This metric is collected only if you have listed it in the ethtool subsection of the metrics_c ollected section of the CloudWatch agent configuration file. For more information, see Collect network performance metrics. Unit: None mem_active The amount of memory that has been used in some way during the last sample period. Unit: Bytes mem_available The amount of memory that is available and can be given instantly to processes. Unit: Bytes mem_available_percent The percentage of memory that is available and can be given instantly to processes. mem_buffered mem_cached Unit: Percent The amount of memory that is being used for buffers. Unit: Bytes The amount of memory that is being used for file caches. Unit: Bytes Metrics collected by the CloudWatch agent on Linux and macOS instances 2741 Amazon CloudWatch Metric mem_free mem_inactive User Guide Description The amount of memory that isn't being used. Unit: Bytes The amount of memory that hasn't been used in some way during the last sample period Unit: Bytes mem_total The total amount of memory. Unit: Bytes mem_used The amount of memory currently in use. Unit: Bytes mem_used_percent The percentage of memory currently in use. Unit: Percent net_bytes_recv The number of bytes received by the network interface. Unit: Bytes The only statistic that should be used for this metric is Sum. Do not use Average. net_bytes_sent The number of bytes sent by the network interface. Unit: Bytes The only statistic that should be used for this metric is Sum. Do not use Average. Metrics collected by the CloudWatch agent on Linux and macOS instances 2742 Amazon CloudWatch Metric net_drop_in net_drop_out net_err_in net_err_out User Guide Description The number of packets received by this network interface that were dropped. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. The number of packets transmitted by this network interface that were dropped. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. The number of receive errors detected by this network interface. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. The number of transmit errors detected by this network interface. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. net_packets_sent The number of packets sent by this network interface. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. Metrics collected by
acw-ug-787
acw-ug.pdf
787
that should be used for this metric is Sum. Do not use Average. The number of receive errors detected by this network interface. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. The number of transmit errors detected by this network interface. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. net_packets_sent The number of packets sent by this network interface. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. Metrics collected by the CloudWatch agent on Linux and macOS instances 2743 Amazon CloudWatch Metric net_packets_recv User Guide Description The number of packets received by this network interface. Unit: Count The only statistic that should be used for this metric is Sum. Do not use Average. netstat_tcp_close The number of TCP connections with no state. Unit: Count netstat_tcp_close_wait The number of TCP connections waiting for a termination request from the client. Unit: Count netstat_tcp_closing The number of TCP connections that are waiting for a termination request with acknowledgment from the client. Unit: Count netstat_tcp_established The number of TCP connections established. Unit: Count netstat_tcp_fin_wait1 The number of TCP connections in the FIN_WAIT1 state during the process of closing a connection. Unit: Count netstat_tcp_fin_wait2 The number of TCP connections in the FIN_WAIT2 state during the process of closing a connection. Unit: Count Metrics collected by the CloudWatch agent on Linux and macOS instances 2744 Amazon CloudWatch Metric netstat_tcp_last_ack User Guide Description The number of TCP connections waiting for the client to send acknowledgment of the connectio n termination message. This is the last state right before the connection is closed down. Unit: Count netstat_tcp_listen The number of TCP ports currently listening for a connection request. Unit: Count netstat_tcp_none The number of TCP connections with inactive clients. Unit: Count netstat_tcp_syn_sent The number of TCP connections waiting for a matching connection request after having sent a netstat_tcp_syn_recv netstat_tcp_time_wait connection request. Unit: Count The number of TCP connections waiting for connection request acknowledgment after having sent and received a connection request. Unit: Count The number of TCP connections currently waiting to ensure that the client received the acknowledgment of its connection termination request. Unit: Count netstat_udp_socket The number of current UDP connections. Unit: Count Metrics collected by the CloudWatch agent on Linux and macOS instances 2745 Amazon CloudWatch Metric Description User Guide processes_blocked The number of processes that are blocked. Unit: Count processes_dead The number of processes that are dead, indicated by processes_idle the X state code on Linux. This metric is not collected on macOS computers. Unit: Count The number of processes that are idle (sleeping for more than 20 seconds). Available only on FreeBSD instances. Unit: Count processes_paging The number of processes that are paging, indicated by the W state code on Linux. This metric is not collected on macOS computers. Unit: Count processes_running The number of processes that are running, indicated by the R state code. Unit: Count processes_sleeping The number of processes that are sleeping, indicated by the S state code. Unit: Count processes_stopped The number of processes that are stopped, indicated by the T state code. Unit: Count Metrics collected by the CloudWatch agent on Linux and macOS instances 2746 Amazon CloudWatch Metric Description User Guide processes_total The total number of processes on the instance. processes_total_threads processes_wait Unit: Count The total number of threads making up the processes. This metric is available only on Linux instances. This metric is not collected on macOS computers. Unit: Count The number of processes that are paging, indicated by the W state code on FreeBSD instances. This metric is available only on FreeBSD instances, and is not available on Linux, Windows Server, or macOS instances. Unit: Count processes_zombies The number of zombie processes, indicated by the Z state code. Unit: Count swap_free The amount of swap space that isn't being used. Unit: Bytes swap_used The amount of swap space currently in use. Unit: Bytes swap_used_percent The percentage of swap space currently in use. Unit: Percent Metrics collected by the CloudWatch agent on Linux and macOS instances 2747 Amazon CloudWatch User Guide Definitions of memory metrics collected by the CloudWatch agent When the CloudWatch agent collects memory metrics, the source is the host's memory management subsystem. For example, the Linux kernel exposes OS-maintained data in /proc. For memory, the data is in /proc/meminfo. Each different operating system and architecture has different calculations of the resources that are used by processes. For more information, see the following sections. During each collection interval, the CloudWatch agent on each instance collects the instance resources and calculates the resources being used by all processes which are running in that instance. This information is reported back to CloudWatch metrics. You can configure the
acw-ug-788
acw-ug.pdf
788
the CloudWatch agent When the CloudWatch agent collects memory metrics, the source is the host's memory management subsystem. For example, the Linux kernel exposes OS-maintained data in /proc. For memory, the data is in /proc/meminfo. Each different operating system and architecture has different calculations of the resources that are used by processes. For more information, see the following sections. During each collection interval, the CloudWatch agent on each instance collects the instance resources and calculates the resources being used by all processes which are running in that instance. This information is reported back to CloudWatch metrics. You can configure the length of the collection interval in the CloudWatch agent configuration file. For more information, see CloudWatch agent configuration file: Agent section. The following list explains how the memory metrics that the CloudWatch agent collects are defined. • Active Memory– Memory that is being used by a process. In other words, the memory used by current running apps. • Available Memory– The memory that can be instantly given to the processes without the system going into swap (also known as virtual memory). • Buffer Memory– The data area shared by hardware devices or program processes that operate at different speeds and priorities. • Cached Memory– Stores program instructions and data that are used repeatedly in the operation of programs that the CPU is likely to need next. • Free Memory– Memory that is not being used at all and is readily available. It is completely free for the system to be used when needed. • Inactive Memory– Pages that have not been accessed "recently". • Total Memory– The size of the actual physical memory RAM. • Used Memory– Memory that is currently in use by programs and processes. Topics • Linux: Metrics collected and calculations used • macOS: Metrics collected and calculations used Memory metric definitions 2748 Amazon CloudWatch • Windows: Metrics collected • Example: Calculating memory metrics on Linux Linux: Metrics collected and calculations used User Guide Metrics collected and units: • Active (Bytes) • Available (Bytes) • Available Percent (Percent) • Buffered (Bytes) • Cached (Bytes) • Free (Bytes) • Inactive (Bytes) • Total (Bytes) • Used (Bytes) • Used Percent (Percent) Used memory = Total Memory - Free Memory - Cached memory - Buffer memory Total memory = Used Memory + Free Memory + Cached memory + Buffer memory macOS: Metrics collected and calculations used Metrics collected and units: • Active (Bytes) • Available (Bytes) • Available Percent (Percent) • Free (Bytes) • Inactive (Bytes) • Total (Bytes) • Used (Bytes) • Used Percent (Percent) Memory metric definitions 2749 Amazon CloudWatch User Guide Available memory = Free Memory + Inactive memory Used memory = Total Memory - Available memory Total memory = Available Memory + Used Memory Windows: Metrics collected The metrics collected on Windows hosts are listed below. All of these metrics have None for Unit. • Available bytes • Cache Faults/sec • Page Faults/sec • Pages/sec There are no calculations used for Windows metrics because the CloudWatch agent parses events from performance counters. Example: Calculating memory metrics on Linux As an example, suppose that entering the cat /proc/meminfo command on a Linux host shows the following results: MemTotal: 3824388 kB MemFree: 462704 kB MemAvailable: 2157328 kB Buffers: 126268 kB Cached: 1560520 kB SReclaimable: 289080 kB> In this example, the CloudWatch agent will collect the following values. All the values that the CloudWatch agent collects and reports are in bytes. • mem_total: 3916173312 bytes • mem_available: 2209103872 bytes (MemFree + Cached) • mem_free: 473808896 bytes • mem_cached: 1893990400 bytes (cached + SReclaimable • mem_used: 1419075584 bytes (MemTotal – (MemFree + Buffers + (Cached + SReclaimable))) Memory metric definitions 2750 Amazon CloudWatch User Guide • mem_buffered: 129667072 bytes • mem_available_percent: 56.41% • mem_used_percent: 36.24% (mem_used / mem_total) * 100 Using the CloudWatch agent with related telemetry Metrics and logs that are sent to CloudWatch can include an optional entity to correlate telemetry. Entities are used in the Explore related pane. The CloudWatch agent sends entities with a service name and environment name included. The agent chooses the service name and environment name from the following data. Service name The agent chooses the service name from the following options, in priority order: • Application Signals instrumentation – The agent sends the service name used by Application Signals. This can be overwritten by changing the OTEL_SERVICE_NAME environment variable used by supported OpenTelemetry instrumentation libraries. • CloudWatch agent configuration – You can configure the agent to use a specific service name. This can be configured at the agent, plugin, metrics, logs, or log file level. • Kubernetes workload name – For Kubernetes workloads, the agent sends the name of the workload for the corresponding pod, in the following priority order. • Deployment name • ReplicaSet name • StatefulSet name • DaemonSet
acw-ug-789
acw-ug.pdf
789
in priority order: • Application Signals instrumentation – The agent sends the service name used by Application Signals. This can be overwritten by changing the OTEL_SERVICE_NAME environment variable used by supported OpenTelemetry instrumentation libraries. • CloudWatch agent configuration – You can configure the agent to use a specific service name. This can be configured at the agent, plugin, metrics, logs, or log file level. • Kubernetes workload name – For Kubernetes workloads, the agent sends the name of the workload for the corresponding pod, in the following priority order. • Deployment name • ReplicaSet name • StatefulSet name • DaemonSet name • CronJob name • Job name • Pod name • Container name • Resource tags from instance metadata – For Amazon EC2 workloads, the agent sends the a name from tags, in the following order. • service Using the CloudWatch agent with related telemetry 2751 Amazon CloudWatch • application • app User Guide You must setup instance metadata for the agent to be able to access tags. • Default – If no other service name is found, the agent will send the name Unknown. Environment name The agent chooses the environment name from the following options, in priority order: • Application Signals instrumentation – The agent sends the environment name used by Application Signals. This can be overwritten by setting a deployment.environment environment variable used by supported OpenTelemetry instrumentation libraries. For example, applications may set the environment variable OTEL_RESOURCE_ATTRIBUTES=deployment.environment=MyEnvironment. • CloudWatch agent configuration – You can configure the agent to use a specific environment name. This can be configured at the agent, plugin, metrics, logs, or log file level. • Cluster name and workspace – For Amazon EKS, eks:cluster-name/Namespace. For native Kubernetes running on Amazon EC2, k8s:cluster-name/Namespace. • Resource tags from instance metadata – For Amazon EC2 workloads, the agent can will use the AutoScalingGroup tag. You must setup instance metadata for the agent to be able to access tags. • By default, Amazon EC2 instances that aren't running Kubernetes will get the environment name ec2:default. Common scenarios with the CloudWatch agent This section provides you with different scenarios that outline how to complete common configuration and customization tasks for the CloudWatch agent. Topics • Running the CloudWatch agent as a different user • How the CloudWatch agent handles sparse log files • Adding custom dimensions to metrics collected by the CloudWatch agent Common scenarios with the CloudWatch agent 2752 Amazon CloudWatch User Guide • Multiple CloudWatch agent configuration files • Aggregating or rolling up metrics collected by the CloudWatch agent • Collecting high-resolution metrics with the CloudWatch agent • Sending metrics, logs, and traces to a different account • Timestamp differences between the unified CloudWatch agent and the earlier CloudWatch Logs agent • Appending OpenTelemetry collector configuration files Running the CloudWatch agent as a different user On Linux servers, the CloudWatch runs as the root user by default. To have the agent run as a different user, use the run_as_user parameter in the agent section in the CloudWatch agent configuration file. This option is available only on Linux servers. If you're already running the agent with the root user and want to change to using a different user, use one of the following procedures. To run the CloudWatch agent as a different user on an EC2 instance running Linux 1. Download and install a new CloudWatch agent package. For more information, see Download the CloudWatch agent package. 2. Create a new Linux user or use the default user named cwagent that the RPM or DEB file created. 3. Provide credentials for this user in one of these ways: • • If the file .aws/credentials exists in the home directory of the root user, you must create a credentials file for the user you are going to use to run the CloudWatch agent. This credentials file will be /home/username/.aws/credentials. Then set the value of the shared_credential_file parameter in common-config.toml to the pathname of the credential file. For more information, see (Optional) Modify the common configuration for proxy or Region information. If the file .aws/credentials does not exist in the home directory of the root user, you can do one of the following: • Create a credentials file for the user you are going to use to run the CloudWatch agent. This credentials file will be /home/username/.aws/credentials. Then set the value of the shared_credential_file parameter in common-config.toml Running the CloudWatch agent as a different user 2753 Amazon CloudWatch User Guide to the pathname of the credential file. For more information, see (Optional) Modify the common configuration for proxy or Region information. • Instead of creating a credentials file, attach an IAM role to the instance. The agent uses this role as the credential provider. 4. In the CloudWatch agent configuration file, add the following line in the agent section: "run_as_user":
acw-ug-790
acw-ug.pdf
790
user you are going to use to run the CloudWatch agent. This credentials file will be /home/username/.aws/credentials. Then set the value of the shared_credential_file parameter in common-config.toml Running the CloudWatch agent as a different user 2753 Amazon CloudWatch User Guide to the pathname of the credential file. For more information, see (Optional) Modify the common configuration for proxy or Region information. • Instead of creating a credentials file, attach an IAM role to the instance. The agent uses this role as the credential provider. 4. In the CloudWatch agent configuration file, add the following line in the agent section: "run_as_user": "username" Make other modifications to the configuration file as needed. For more information, see Create the CloudWatch agent configuration file 5. Give the user the required permissions. The user must have Read (r) permissions for the log files to be collected, and must have Execute (x) permission on every directory in the log files' path. 6. Start the agent with the configuration file that you just modified. sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch- config -m ec2 -s -c file:configuration-file-path To run the CloudWatch agent as a different user on an on-premises server running Linux 1. Download and install a new CloudWatch agent package. For more information, see Download the CloudWatch agent package. 2. Create a new Linux user or use the default user named cwagent that the RPM or DEB file created. 3. 4. Store the credentials of this user to a path that the user can access, such as / home/username/.aws/credentials. Set the value of the shared_credential_file parameter in common-config.toml to the pathname of the credential file. For more information, see (Optional) Modify the common configuration for proxy or Region information. 5. In the CloudWatch agent configuration file, add the following line in the agent section: "run_as_user": "username" Make other modifications to the configuration file as needed. For more information, see Create the CloudWatch agent configuration file Running the CloudWatch agent as a different user 2754 Amazon CloudWatch User Guide 6. Give the user required permissions. The user must have Read (r) permissions for the log files to be collected, and must have Execute (x) permission on every directory in the log files' path. 7. Start the agent with the configuration file that you just modified. sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch- config -m ec2 -s -c file:configuration-file-path How the CloudWatch agent handles sparse log files Sparse files are files with both empty blocks and real contents. A sparse file uses disk space more efficiently by writing brief information representing the empty blocks to disk instead of the actual null bytes which makes up the block. This makes the actual size of a sparse file usually much smaller than its apparent size. However, the CloudWatch agent doesn’t treat sparse files differently than it treats normal files. When the agent reads a sparse file, the empty blocks are treated as "real" blocks filled with null bytes. Because of this, the CloudWatch agent publishes as many bytes as the apparent size of a sparse file to CloudWatch. Configuring the CloudWatch agent to publish a sparse file can cause higher than expected CloudWatch costs, so we recommend not to do so. For example, /var/logs/lastlog in Linux is usually a very sparse file, and we recommend that you don't publish it to CloudWatch. Adding custom dimensions to metrics collected by the CloudWatch agent To add custom dimensions such as tags to metrics collected by the agent, add the append_dimensions field to the section of the agent configuration file that lists those metrics. For example, the following example section of the configuration file adds a custom dimension named stackName with a value of Prod to the cpu and disk metrics collected by the agent. "cpu":{ "resources":[ "*" ], "measurement":[ "cpu_usage_guest", How the CloudWatch agent handles sparse log files 2755 Amazon CloudWatch User Guide "cpu_usage_nice", "cpu_usage_idle" ], "totalcpu":false, "append_dimensions":{ "stackName":"Prod" } }, "disk":{ "resources":[ "/", "/tmp" ], "measurement":[ "total", "used" ], "append_dimensions":{ "stackName":"Prod" } } Remember that any time you change the agent configuration file, you must restart the agent to have the changes take effect. Multiple CloudWatch agent configuration files On both Linux servers and Windows servers, you can set up the CloudWatch agent to use multiple configuration files. For example, you can use a common configuration file that collects a set of metrics, logs, and traces that you always want to collect from all servers in your infrastructure. You can then use additional configuration files that collect metrics from certain applications or in certain situations. To set this up, first create the configuration files that you want to use. Any configuration files that will be used together on the same server must have different file names. You can store the configuration files on servers or in Parameter Store. Start the CloudWatch agent using the fetch-config option and
acw-ug-791
acw-ug.pdf
791
files. For example, you can use a common configuration file that collects a set of metrics, logs, and traces that you always want to collect from all servers in your infrastructure. You can then use additional configuration files that collect metrics from certain applications or in certain situations. To set this up, first create the configuration files that you want to use. Any configuration files that will be used together on the same server must have different file names. You can store the configuration files on servers or in Parameter Store. Start the CloudWatch agent using the fetch-config option and specify the first configuration file. To append the second configuration file to the running agent, use the same command but with the append-config option. All metrics, logs, and traces listed in either configuration file are collected. The following example commands illustrate this scenario using configurations stores as Multiple CloudWatch agent configuration files 2756 Amazon CloudWatch User Guide files. The first line starts the agent using the infrastructure.json configuration file, and the second line appends the app.json configuration file. The following example commands are for Linux. /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/tmp/infrastructure.json /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a append-config -m ec2 -s -c file:/tmp/app.json The following example commands are for Windows Server. & "C:\Program Files\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1" -a fetch-config -m ec2 -s -c file:"C:\Program Files\Amazon\AmazonCloudWatchAgent \infrastructure.json" & "C:\Program Files\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1" -a append-config -m ec2 -s -c file:"C:\Program Files\Amazon\AmazonCloudWatchAgent \app.json" The following example configuration files illustrate a use for this feature. The first configuration file is used for all servers in the infrastructure, and the second collects only logs from a certain application and is appended to servers running that application. infrastructure.json { "metrics": { "metrics_collected": { "cpu": { "resources": [ "*" ], "measurement": [ "usage_active" ], "totalcpu": true }, "mem": { "measurement": [ Multiple CloudWatch agent configuration files 2757 Amazon CloudWatch "used_percent" ] } } }, "logs": { "logs_collected": { "files": { "collect_list": [ { User Guide "file_path": "/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch- agent.log", "log_group_name": "amazon-cloudwatch-agent.log" }, { "file_path": "/var/log/messages", "log_group_name": "/var/log/messages" } ] } } } } app.json { "logs": { "logs_collected": { "files": { "collect_list": [ { "file_path": "/app/app.log*", "log_group_name": "/app/app.log" } ] } } } } Any configuration files appended to the configuration must have different file names from each other and from the initial configuration file. If you use append-config with a configuration Multiple CloudWatch agent configuration files 2758 Amazon CloudWatch User Guide file with the same file name as a configuration file that the agent is already using, the append command overwrites the information from the first configuration file instead of appending to it. This is true even if the two configuration files with the same file name are on different file paths. The preceding example shows the use of two configuration files, but there is no limit to the number of configuration files that you can append to the agent configuration. You can also mix the use of configuration files located on servers and configurations located in Parameter Store. Aggregating or rolling up metrics collected by the CloudWatch agent To aggregate or roll up metrics collected by the agent, add an aggregation_dimensions field to the section for that metric in the agent configuration file. For example, the following configuration file snippet rolls up metrics on the AutoScalingGroupName dimension. The metrics from all instances in each Auto Scaling group are aggregated and can be viewed as a whole. "metrics": { "cpu":{...} "disk":{...} "aggregation_dimensions" : [["AutoScalingGroupName"]] } To roll up along the combination of each InstanceId and InstanceType dimensions in addition to rolling up on the Auto Scaling group name, add the following. "metrics": { "cpu":{...} "disk":{...} "aggregation_dimensions" : [["AutoScalingGroupName"], ["InstanceId", "InstanceType"]] } To roll up metrics into one collection instead, use []. "metrics": { "cpu":{...} "disk":{...} "aggregation_dimensions" : [[]] } Aggregating or rolling up metrics collected by the CloudWatch agent 2759 Amazon CloudWatch User Guide Remember that any time you change the agent configuration file, you must restart the agent to have the changes take effect. Collecting high-resolution metrics with the CloudWatch agent The metrics_collection_interval field specifies the time interval for the metrics collected, in seconds. By specifying a value of less than 60 for this field, the metrics are collected as high- resolution metrics. For example, if your metrics should all be high-resolution and collected every 10 seconds, specify 10 as the value for metrics_collection_interval under the agent section as a global metrics collection interval. "agent": { "metrics_collection_interval": 10 } Alternatively, the following example sets the cpu metrics to be collected every second, and all other metrics are collected every minute. "agent":{ "metrics_collection_interval": 60 }, "metrics":{ "metrics_collected":{ "cpu":{ "resources":[ "*" ], "measurement":[ "cpu_usage_guest" ], "totalcpu":false, "metrics_collection_interval": 1 }, "disk":{ "resources":[ "/", "/tmp" ], "measurement":[ "total", Collecting high-resolution metrics with the CloudWatch agent 2760 Amazon CloudWatch "used" ] } } } User Guide Remember that
acw-ug-792
acw-ug.pdf
792
For example, if your metrics should all be high-resolution and collected every 10 seconds, specify 10 as the value for metrics_collection_interval under the agent section as a global metrics collection interval. "agent": { "metrics_collection_interval": 10 } Alternatively, the following example sets the cpu metrics to be collected every second, and all other metrics are collected every minute. "agent":{ "metrics_collection_interval": 60 }, "metrics":{ "metrics_collected":{ "cpu":{ "resources":[ "*" ], "measurement":[ "cpu_usage_guest" ], "totalcpu":false, "metrics_collection_interval": 1 }, "disk":{ "resources":[ "/", "/tmp" ], "measurement":[ "total", Collecting high-resolution metrics with the CloudWatch agent 2760 Amazon CloudWatch "used" ] } } } User Guide Remember that any time you change the agent configuration file, you must restart the agent to have the changes take effect. Sending metrics, logs, and traces to a different account To have the CloudWatch agent send the metrics, logs, or traces to a different account, specify a role_arn parameter in the agent configuration file on the sending server. The role_arn value specifies an IAM role in the target account that the agent uses when sending data to the target account. This role enables the sending account to assume a corresponding role in the target account when delivering the metrics or logs to the target account. You can also specify separate role_arn strings in the agent configuration file: one to use when sending metrics, another for sending logs, and another for sending traces. The following example of part of the agent section of the configuration file sets the agent to use CrossAccountAgentRole when sending data to a different account. { "agent": { "credentials": { "role_arn": "arn:aws:iam::123456789012:role/CrossAccountAgentRole" } }, ..... } Alternatively, the following example sets different roles for the sending account to use for sending metrics, logs, and traces: "metrics": { "credentials": { "role_arn": "RoleToSendMetrics" }, "metrics_collected": {.... Sending metrics, logs, and traces to a different account 2761 Amazon CloudWatch User Guide "logs": { "credentials": { "role_arn": "RoleToSendLogs" }, .... Policies needed When you specify a role_arn in the agent configuration file, you must also make sure the IAM roles of the sending and target accounts have certain policies. The roles in both the sending and target accounts should have CloudWatchAgentServerPolicy. For more information about assigning this policy to a role, see Create IAM roles to use with the CloudWatch agent on Amazon EC2 instances. The role in the sending account also must include the following policy. You add this policy on the Permissions tab in the IAM console when you edit the role. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sts:AssumeRole" ], "Resource": [ "arn:aws:iam::target-account-ID:role/agent-role-in-target-account" ] } ] } The role in the target account must include the following policy so that it recognizes the IAM role used by the sending account. You add this policy on the Trust relationships tab in the IAM console when you edit the role. The role in the target account where you add this policy is the role you created in Create IAM roles and users for use with CloudWatch agent. This role is the role specified in agent-role-in-target-account in the policy used by the sending account. { "Version": "2012-10-17", Sending metrics, logs, and traces to a different account 2762 Amazon CloudWatch "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ User Guide "arn:aws:iam::sending-account-ID:role/role-in-sender-account" ] }, "Action": "sts:AssumeRole" } ] } Timestamp differences between the unified CloudWatch agent and the earlier CloudWatch Logs agent The CloudWatch agent supports a different set of symbols for timestamp formats, compared to the earlier CloudWatch Logs agent. These differences are shown in the following table. Symbols supported by both agents Symbols supported only by unified CloudWatch agent Symbols supported only by earlier CloudWatch Logs agent %-d, %-l, %-m, %-M, %-S %c,%j, %U, %W, %w %A, %a, %b, %B, %d, %f, %H, %l, %m, %M, %p, %S, %y, %Y, %Z, %z For more information about the meanings of the symbols supported by the new CloudWatch agent, see CloudWatch Agent Configuration File: Logs Section in the Amazon CloudWatch User Guide. For information about symbols supported by the CloudWatch Logs agent, see Agent Configuration File in the Amazon CloudWatch Logs User Guide. Appending OpenTelemetry collector configuration files The CloudWatch agent supports supplemental OpenTelemetry collector configuration files alongside its own configuration files. This feature allows you to use CloudWatch agent features such as CloudWatch Application Signals or Container Insights through the CloudWatch agent configuration and bring in your existing OpenTelemetry collector configuration with a single agent. Timestamp differences between the unified CloudWatch agent and the earlier CloudWatch Logs agent 2763 Amazon CloudWatch User Guide To prevent merge conflicts with pipelines automatically created by CloudWatch agent, we recommend that you add a custom suffix to each of the components and pipelines in your OpenTelemetry collector configuration. receivers: otlp/custom-suffix: protocols: http: exporters: awscloudwatchlogs/custom-suffix: log_group_name: "test-group" log_stream_name: "test-stream" service: pipelines: logs/custom-suffix: receivers: [otlp/custom-suffix] exporters:
acw-ug-793
acw-ug.pdf
793
files. This feature allows you to use CloudWatch agent features such as CloudWatch Application Signals or Container Insights through the CloudWatch agent configuration and bring in your existing OpenTelemetry collector configuration with a single agent. Timestamp differences between the unified CloudWatch agent and the earlier CloudWatch Logs agent 2763 Amazon CloudWatch User Guide To prevent merge conflicts with pipelines automatically created by CloudWatch agent, we recommend that you add a custom suffix to each of the components and pipelines in your OpenTelemetry collector configuration. receivers: otlp/custom-suffix: protocols: http: exporters: awscloudwatchlogs/custom-suffix: log_group_name: "test-group" log_stream_name: "test-stream" service: pipelines: logs/custom-suffix: receivers: [otlp/custom-suffix] exporters: [awscloudwatchlogs/custom-suffix] To configure the CloudWatch agent, start the CloudWatch agent using the fetch-config option and specify the CloudWatch agent’s configuration file. CloudWatch agent requires at least one CloudWatch agent configuration file. /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -c file:/tmp/agent.json -s Next, use the append-config option while specifying the OpenTelemetry collector configuration file. /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a append-config -c file:/tmp/otel.yaml -s The agent merges the two configuration files on start up and logs the resolved configuration. Troubleshooting the CloudWatch agent You can use the information in this section to troubleshoot issues you might encounter with the CloudWatch agent. Troubleshooting the CloudWatch agent 2764 Amazon CloudWatch Topics • CloudWatch agent command line parameters • Install the CloudWatch agent using Run Command fails • The CloudWatch agent won't start • Verify that the CloudWatch agent is running User Guide • The CloudWatch agent won't start, and the error mentions an Amazon EC2 Region • The CloudWatch agent won't start on Windows Server • Where are the metrics? • The CloudWatch agent takes a long time to run in a container or logs a hop limit error • I updated my agent configuration but don’t see the new metrics or logs in the CloudWatch console • CloudWatch agent files and locations • Finding information about CloudWatch agent versions • Logs generated by the CloudWatch agent • Stopping and restarting the CloudWatch agent CloudWatch agent command line parameters To see the full list of parameters supported by the CloudWatch agent, enter the following at the command line at a computer where you have it installed: amazon-cloudwatch-agent-ctl -help Install the CloudWatch agent using Run Command fails To install the CloudWatch agent using Systems Manager Run Command, the SSM Agent on the target server must be version 2.2.93.0 or later of the SSM Agent agent. If your SSM Agent isn't the correct version, you might see errors that include the following messages: no latest version found for package AmazonCloudWatchAgent on platform linux failed to download installation package reliably CloudWatch agent command line parameters 2765 Amazon CloudWatch User Guide For information about updating your SSM Agent version, see Installing and Configuring SSM Agent in the AWS Systems Manager User Guide. The CloudWatch agent won't start If the CloudWatch agent fails to start, there might be an issue in your configuration. Configuration information is logged in the configuration-validation.log file. This file is located in /opt/ aws/amazon-cloudwatch-agent/logs/configuration-validation.log on Linux servers and in $Env:ProgramData\Amazon\AmazonCloudWatchAgent\Logs\configuration- validation.log on servers running Windows Server. Verify that the CloudWatch agent is running You can query the CloudWatch agent to find whether it's running or stopped. You can use AWS Systems Manager to do this remotely. You can also use the command line, but only to check the local server. To query the status of the CloudWatch agent using Run Command 1. Open the Systems Manager console at https://console.aws.amazon.com/systems-manager/. 2. In the navigation pane, choose Run Command. -or- If the AWS Systems Manager home page opens, scroll down and choose Explore Run Command. 3. Choose Run command. 4. 5. 6. In the Command document list, choose the button next to AmazonCloudWatch- ManageAgent. In the Action list, choose status. For Optional Configuration Source choose default and keep Optional Configuration Location blank. 7. In the Target area, choose the instance to check. 8. Choose Run. If the agent is running, the output resembles the following. The CloudWatch agent won't start 2766 Amazon CloudWatch User Guide { "status": "running", "starttime": "2017-12-12T18:41:18", "version": "1.73.4" } If the agent is stopped, the "status" field displays "stopped". To query the status of the CloudWatch agent locally using the command line • On a Linux server, enter the following: sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status On a server running Windows Server, enter the following in PowerShell as an administrator: & $Env:ProgramFiles\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1 -m ec2 -a status The CloudWatch agent won't start, and the error mentions an Amazon EC2 Region If the agent doesn't start and the error message mentions an Amazon EC2 Region endpoint, you might have configured the agent to need access to the Amazon EC2 endpoint without granting that access. For example, if you specify a value for the append_dimensions parameter in the agent configuration file that depends on Amazon EC2 metadata and you use proxies, you must
acw-ug-794
acw-ug.pdf
794
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status On a server running Windows Server, enter the following in PowerShell as an administrator: & $Env:ProgramFiles\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1 -m ec2 -a status The CloudWatch agent won't start, and the error mentions an Amazon EC2 Region If the agent doesn't start and the error message mentions an Amazon EC2 Region endpoint, you might have configured the agent to need access to the Amazon EC2 endpoint without granting that access. For example, if you specify a value for the append_dimensions parameter in the agent configuration file that depends on Amazon EC2 metadata and you use proxies, you must make sure that the server can access the endpoint for Amazon EC2. For more information about these endpoints, see Amazon Elastic Compute Cloud (Amazon EC2) in the Amazon Web Services General Reference. The CloudWatch agent won't start on Windows Server On Windows Server, you might see the following error: Start-Service : Service 'Amazon CloudWatch Agent (AmazonCloudWatchAgent)' cannot be started due to the following The CloudWatch agent won't start, and the error mentions an Amazon EC2 Region 2767 Amazon CloudWatch User Guide error: Cannot start service AmazonCloudWatchAgent on computer '.'. At C:\Program Files\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1:113 char:12 + $svc | Start-Service + ~~~~~~~~~~~~~ + CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException + FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand To fix this, first make sure that the server service is running. This error can be seen if the agent tries to start when the server service isn't running. If the server service is already running, the following may be the issue. On some Windows Server installations, the CloudWatch agent takes more than 30 seconds to start. Because Windows Server, by default, allows only 30 seconds for services to start, this causes the agent to fail with an error similar to the following: To fix this issue, increase the service timeout value. For more information, see A service does not start, and events 7000 and 7011 are logged in the Windows event log. Where are the metrics? If the CloudWatch agent has been running but you can't find metrics collected by it in the AWS Management Console or the AWS CLI, confirm that you're using the correct namespace. By default, the namespace for metrics collected by the agent is CWAgent. You can customize this namespace using the namespace field in the metrics section of the agent configuration file. If you don't see the metrics that you expect, check the configuration file to confirm the namespace being used. When you first download the CloudWatch agent package, the agent configuration file is amazon- cloudwatch-agent.json. This file is in the directory where you ran the configuration wizard, or you might have moved it to a different directory. If you use the configuration wizard, the agent configuration file output from the wizard is named config.json. For more information about the configuration file, including the namespace field, see CloudWatch agent configuration file: Metrics section. Where are the metrics? 2768 Amazon CloudWatch User Guide The CloudWatch agent takes a long time to run in a container or logs a hop limit error When you run the CloudWatch agent as a container service and want to add Amazon EC2 metric dimensions to all metrics collected by the agent, you might see the following errors in version v1.247354.0 of the agent: 2022-06-07T03:36:11Z E! [processors.ec2tagger] ec2tagger: Unable to retrieve Instance Metadata Tags. This plugin must only be used on an EC2 instance. 2022-06-07T03:36:11Z E! [processors.ec2tagger] ec2tagger: Please increase hop limit to 2 by following this document https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ configuring-instance-metadata-options.html#configuring-IMDS-existing-instances. 2022-06-07T03:36:11Z E! [telegraf] Error running agent: could not initialize processor ec2tagger: EC2MetadataRequestError: failed to get EC2 instance identity document caused by: EC2MetadataError: failed to make EC2Metadata request status code: 401, request id: caused by: You might see this error if the agent tries to get metadata from IMDSv2 inside a container without an appropriate hop limit. In versions of the agent earlier than v1.247354.0, you can experience this issue without seeing the log message. To solve this, increase the hop limit to 2 by following the instructions in Configure the instance metadata options. I updated my agent configuration but don’t see the new metrics or logs in the CloudWatch console If you update your CloudWatch agent configuration file, the next time that you start the agent, you need to use the fetch-config option. For example, if you stored the updated file on the local computer, enter the following command: sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config - s -m ec2 -c file:configuration-file-path CloudWatch agent files and locations The following table lists the files installed by and used with the CloudWatch agent, along with their locations on servers running Linux or Windows Server. The CloudWatch agent takes a long time to run in a container or logs a hop limit error 2769 Amazon CloudWatch User Guide File Linux location Windows Server location The control script
acw-ug-795
acw-ug.pdf
795
that you start the agent, you need to use the fetch-config option. For example, if you stored the updated file on the local computer, enter the following command: sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config - s -m ec2 -c file:configuration-file-path CloudWatch agent files and locations The following table lists the files installed by and used with the CloudWatch agent, along with their locations on servers running Linux or Windows Server. The CloudWatch agent takes a long time to run in a container or logs a hop limit error 2769 Amazon CloudWatch User Guide File Linux location Windows Server location The control script that controls starting, stopping, and restarting the agent. /opt/aws/amazon-cl $Env:ProgramFiles\ oudwatch-agent/bin Amazon\AmazonCloud /amazon-cloudwatch- agent-ctl or /usr/bin/ WatchAgent\amazon- cloudwatch-agent-c amazon-cloudwatch- tl.ps1 agent-ctl The log file the agent writes to. You might need to attach this when contacting AWS Support. /opt/aws/amazon-cl $Env:ProgramData\A oudwatch-agent/log mazon\AmazonCloudW s/amazon-cloudwatc h-agent.log or /var/ atchAgent\Logs\ama zon-cloudwatch-age log/amazon/amazon- nt.log cloudwatch-agent/ amazon-cloudwatch- agent.log Agent configuration validatio n file. /opt/aws/amazon-cl $Env:ProgramData\A oudwatch-agent/log mazon\AmazonCloudW s/configuration- validation.log or / atchAgent\Logs\con figuration-validat var/log/amazon/am ion.log azon-cloudwatch-ag ent/configuration- validation.log The JSON file used to configure the agent immediately after the wizard creates it. For more informati on, see Create the CloudWatc h agent configuration file. /opt/aws/amazon-cl $Env:ProgramFiles\ oudwatch-agent/bin/ Amazon\AmazonCloud config.json WatchAgent\config. json The JSON file used to configure the agent if this /opt/aws/amazon-cl $Env:ProgramData\A oudwatch-agent/etc mazon\AmazonCloudW configuration file has been /amazon-cloudwatch- atchAgent\amazon-c CloudWatch agent files and locations 2770 Amazon CloudWatch User Guide File Linux location Windows Server location downloaded from Parameter agent.json or /etc/amaz loudwatch-agent.js Store. on/amazon-cloudwat on ch-agent/amazon-cl oudwatch-agent.json The TOML file used to specify Region and credentia /opt/aws/amazon-cl $Env:ProgramData\A oudwatch-agent/etc mazon\AmazonCloudW l information to be used by the agent, overriding system /common-config.toml or /etc/amazon/amazon atchAgent\common-c onfig.toml defaults. -cloudwatch-agent/ common-config.toml The TOML file that contains the converted contents of the JSON configura tion file. The amazon-cl /opt/aws/amazon-cl $Env:ProgramData\A oudwatch-agent/etc mazon\AmazonCloudW /amazon-cloudwatch- agent.toml or /etc/amaz atchAgent\amazon-c loudwatch-agent.to oudwatch-agent-ctl on/amazon-cloudwat ml script generates this file. ch-agent/amazon-cl oudwatch-agent.toml Users should not directly modify this file. It can be useful for verifying that JSON to TOML translation was successful. The YAML file that contains the converted contents of the JSON configura /opt/aws/amazon-cl $Env:ProgramData\A oudwatch-agent/etc mazon\AmazonCloudW /amazon-cloudwatch atchAgent\amazon-c tion file. The amazon-cl -agent.yaml or / loudwatch-agent.ya oudwatch-agent-ctl script generates this file. You etc/amazon/amazon ml -cloudwatch-agent/ should not directly modify amazon-cloudwatch- this file. This file can be useful for verifying that the JSON to YAML translation was successful. agent.yaml CloudWatch agent files and locations 2771 Amazon CloudWatch User Guide Finding information about CloudWatch agent versions To find the version number of the CloudWatch agent on a Linux server, enter the following command: sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a status To find the version number of the CloudWatch agent on Windows Server, enter the following command: & $Env:ProgramFiles\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1 -m ec2 -a status Note Using this command is the correct way to find the version of the CloudWatch agent. If you use Programs and Features in the Control Panel, you will see an incorrect version number. You can also download a README file about the latest changes to the agent, and a file that indicates the version number that is currently available for download. These files are in the following locations: • https://amazoncloudwatch-agent.s3.amazonaws.com/info/latest/RELEASE_NOTES or https://amazoncloudwatch-agent-region.s3.region.amazonaws.com/info/ latest/RELEASE_NOTES • https://amazoncloudwatch-agent.s3.amazonaws.com/info/ latest/CWAGENT_VERSION or https://amazoncloudwatch- agent-region.s3.region.amazonaws.com/info/latest/CWAGENT_VERSION Logs generated by the CloudWatch agent The agent generates a log while it runs. This log includes troubleshooting information. This log is the amazon-cloudwatch-agent.log file. This file is located in /opt/aws/amazon- cloudwatch-agent/logs/amazon-cloudwatch-agent.log on Linux servers and in $Env:ProgramData\Amazon\AmazonCloudWatchAgent\Logs\amazon-cloudwatch- agent.log on servers running Windows Server. Finding information about CloudWatch agent versions 2772 Amazon CloudWatch User Guide You can configure the agent to log additional details in the amazon-cloudwatch-agent.log file. In the agent configuration file, in the agent section, set the debug field to true, then reconfigure and restart the CloudWatch agent. To disable the logging of this extra information, set the debug field to false. Then, reconfigure and restart the agent. For more information, see Manually create or edit the CloudWatch agent configuration file. In versions 1.247350.0 and later of the CloudWatch agent, you can optionally set the aws_sdk_log_level field in the agent section of the agent configuration file to one or more of the following options. Separate multiple options with the | character. • LogDebug • LogDebugWithSigning • LogDebugWithHTTPBody • LogDebugRequestRetries • LogDebugWithEventStreamBody For more information about these options, see LogLevelType. Stopping and restarting the CloudWatch agent You can manually stop the CloudWatch agent using either AWS Systems Manager or the command line. To stop the CloudWatch agent using Run Command 1. Open the Systems Manager console at https://console.aws.amazon.com/systems-manager/. 2. In the navigation pane, choose Run Command. -or- If the AWS Systems Manager home page opens, scroll down and choose Explore Run Command. 3. Choose Run command. 4. 5. 6. In the Command document list, choose AmazonCloudWatch-ManageAgent. In the Targets area, choose the instance
acw-ug-796
acw-ug.pdf
796
LogDebug • LogDebugWithSigning • LogDebugWithHTTPBody • LogDebugRequestRetries • LogDebugWithEventStreamBody For more information about these options, see LogLevelType. Stopping and restarting the CloudWatch agent You can manually stop the CloudWatch agent using either AWS Systems Manager or the command line. To stop the CloudWatch agent using Run Command 1. Open the Systems Manager console at https://console.aws.amazon.com/systems-manager/. 2. In the navigation pane, choose Run Command. -or- If the AWS Systems Manager home page opens, scroll down and choose Explore Run Command. 3. Choose Run command. 4. 5. 6. In the Command document list, choose AmazonCloudWatch-ManageAgent. In the Targets area, choose the instance where you installed the CloudWatch agent. In the Action list, choose stop. 7. Keep Optional Configuration Source and Optional Configuration Location blank. Stopping and restarting the CloudWatch agent 2773 Amazon CloudWatch 8. Choose Run. User Guide To stop the CloudWatch agent locally using the command line • On a Linux server, enter the following: sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a stop On a server running Windows Server, enter the following in PowerShell as an administrator: & $Env:ProgramFiles\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1 -m ec2 -a stop To restart the agent, follow the instructions in (Optional) Modify the common configuration and named profile for CloudWatch agent. Stopping and restarting the CloudWatch agent 2774 Amazon CloudWatch User Guide Embedding metrics within logs The CloudWatch embedded metric format allows you to generate custom metrics asynchronously in the form of logs written to CloudWatch Logs. You can embed custom metrics alongside detailed log event data, and CloudWatch automatically extracts the custom metrics so that you can visualize and alarm on them, for real-time incident detection. Additionally, the detailed log events associated with the extracted metrics can be queried using CloudWatch Logs Insights to provide deep insights into the root causes of operational events. Embedded metric format helps you generate actionable custom metrics from ephemeral resources such as Lambda functions and containers. By using the embedded metric format to send logs from these ephemeral resources, you can now easily create custom metrics without having to instrument or maintain separate code, while gaining powerful analytical capabilities on your log data. No setup is required to use the embedded metric format. Either structure your logs by following the Embedded metric format specification, or generate them using our client libraries and send them to CloudWatch Logs using the PutLogEvents API or the CloudWatch agent. To generate metrics from logs with embedded metric format, you need the logs:PutLogEvents permission but you don't need to also have the cloudwatch:PutMetricData permission. Charges are incurred for logs ingestion and archival, and custom metrics that are generated. For more information, see Amazon CloudWatch Pricing. Note Be careful when configuring your metric extraction as it impacts your custom metric usage and corresponding bill. If you unintentionally create metrics based on high- cardinality dimensions (such as requestId), the embedded metric format will by design create a custom metric corresponding to each unique dimension combination. For more information, see Dimensions. The following topics describe how to publish logs using the embedded metric format, view your metrics and logs in the console, and set alarms on metrics created with the embedded metric format. Topics 2775 Amazon CloudWatch User Guide • Publishing logs with the embedded metric format • Viewing your metrics and logs in the console • Setting alarms on metrics created with the embedded metric format Publishing logs with the embedded metric format You can generate embedded metric format logs using the following methods: • Generate and send the logs by using the open-sourced client libraries. • Manually generate the logs using the embedded metric format specification, and then use the CloudWatch agent or the PutLogEvents API to send the logs. The following topics provide more information about embedded metrics. Topics • Creating logs in embedded metric format using the client libraries • Specification: Embedded metric format • Using the PutLogEvents API to send manually-created embedded metric format logs • Using the CloudWatch agent to send embedded metric format logs • Using the embedded metric format with AWS Distro for OpenTelemetry Creating logs in embedded metric format using the client libraries You can use the open-sourced client libraries that Amazon provides to create embedded metric format logs. Currently, these libraries are available for the languages in the following list. Full examples for different setups can be found in our client libraries under /examples. The libraries and the instructions for how to use them are located on Github. Use the following links. • Node.Js Note For Node.js, versions 4.1.1+, 3.0.2+, 2.0.7+ are required for use with the Lambda JSON log format. Using previous versions in such Lambda environments will lead to metric loss. For more information, see Accessing Amazon CloudWatch logs for AWS Lambda. Publishing logs with the embedded metric format 2776 Amazon CloudWatch • Python • Java • C# User Guide Client
acw-ug-797
acw-ug.pdf
797
for the languages in the following list. Full examples for different setups can be found in our client libraries under /examples. The libraries and the instructions for how to use them are located on Github. Use the following links. • Node.Js Note For Node.js, versions 4.1.1+, 3.0.2+, 2.0.7+ are required for use with the Lambda JSON log format. Using previous versions in such Lambda environments will lead to metric loss. For more information, see Accessing Amazon CloudWatch logs for AWS Lambda. Publishing logs with the embedded metric format 2776 Amazon CloudWatch • Python • Java • C# User Guide Client libraries are meant to work out of the box with the CloudWatch agent. Generated embedded metric format logs are sent to the CloudWatch agent, which then aggregates and publishes them to CloudWatch Logs for you. Note When using Lambda, no agent is required to send the logs to CloudWatch. Anything logged to STDOUT is sent to CloudWatch Logs via the Lambda Logging Agent. Specification: Embedded metric format The CloudWatch embedded metric format is a JSON specification used to instruct CloudWatch Logs to automatically extract metric values embedded in structured log events. You can use CloudWatch to graph and create alarms on the extracted metric values. This section describes embedded metric format specification conventions and the embedded metric format document structure. Embedded metric format specification conventions The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this format specification are to be interpreted as described in Key Words RFC2119. The terms "JSON", "JSON text", "JSON value", "member", "element", "object", "array", "number", "string", "boolean", "true", "false", and "null" in this format specification are to be interpreted as defined in JavaScript Object Notation RFC8259. Note If you plan to create alarms on metrics created using embedded metric format, see Setting alarms on metrics created with the embedded metric format for recommendations. Specification: Embedded metric format 2777 Amazon CloudWatch User Guide Embedded metric format document structure This section describes the structure of an embedded metric format document. Embedded metric format documents are defined in JavaScript Object Notation RFC8259. Unless otherwise noted, objects defined by this specification MUST NOT contain any additional members. Members not recognized by this specification MUST be ignored. Members defined in this specification are case-sensitive. The embedded metric format is subject to the same limits as standard CloudWatch Logs events and are limited to a maximum size of 1 MB. With the embedded metric format, you can track the processing of your EMF logs by metrics that are published in the AWS/Logs namespace of your account. These can be used to track failed metric generation from EMF, as well as whether failures happen due to parsing or validation. For more details see Monitoring with CloudWatch metrics. Root node The LogEvent message MUST be a valid JSON object with no additional data at the beginning or end of the LogEvent message string. For more information about the LogEvent structure, see InputLogEvent. Embedded metric format documents MUST contain the following top-level member on the root node. This is a Metadata object object. { "_aws": { "CloudWatchMetrics": [ ... ] } } The root node MUST contain all Target members members defined by the references in the MetricDirective object. The root node MAY contain any other members that are not included in the above requirements. The values of these members MUST be valid JSON types. Specification: Embedded metric format 2778 Amazon CloudWatch Metadata object User Guide The _aws member can be used to represent metadata about the payload that informs downstream services how they should process the LogEvent. The value MUST be an object and MUST contain the following members: • CloudWatchMetrics— An array of MetricDirective object used to instruct CloudWatch to extract metrics from the root node of the LogEvent. { "_aws": { "CloudWatchMetrics": [ ... ] } } • Timestamp— A number representing the time stamp used for metrics extracted from the event. Values MUST be expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. { "_aws": { "Timestamp": 1559748430481 } } MetricDirective object The MetricDirective object instructs downstream services that the LogEvent contains metrics that will be extracted and published to CloudWatch. MetricDirectives MUST contain the following members: • Namespace— A string representing the CloudWatch namespace for the metric. • Dimensions— A DimensionSet array. • Metrics— An array of MetricDefinition objects. This array MUST NOT contain more than 100 MetricDefinition objects. Specification: Embedded metric format 2779 Amazon CloudWatch DimensionSet array User Guide A DimensionSet is an array of strings containing the dimension keys that will be applied to all metrics in the document. The values within this array MUST also be members on the root-node— referred to as the Target members A DimensionSet MUST NOT contain more than 30 dimension
acw-ug-798
acw-ug.pdf
798
to CloudWatch. MetricDirectives MUST contain the following members: • Namespace— A string representing the CloudWatch namespace for the metric. • Dimensions— A DimensionSet array. • Metrics— An array of MetricDefinition objects. This array MUST NOT contain more than 100 MetricDefinition objects. Specification: Embedded metric format 2779 Amazon CloudWatch DimensionSet array User Guide A DimensionSet is an array of strings containing the dimension keys that will be applied to all metrics in the document. The values within this array MUST also be members on the root-node— referred to as the Target members A DimensionSet MUST NOT contain more than 30 dimension keys. A DimensionSet MAY be empty. The target member MUST have a string value. This value MUST NOT contain more than 1024 characters. The target member defines a dimension that will be published as part of the metric identity. Every DimensionSet used creates a new metric in CloudWatch. For more information about dimensions, see Dimension and Dimensions. { "_aws": { "CloudWatchMetrics": [ { "Dimensions": [ [ "functionVersion" ] ], ... } ] }, "functionVersion": "$LATEST" } Note Be careful when configuring your metric extraction as it impacts your custom metric usage and corresponding bill. If you unintentionally create metrics based on high- cardinality dimensions (such as requestId), the embedded metric format will by design create a custom metric corresponding to each unique dimension combination. For more information, see Dimensions. MetricDefinition object A MetricDefinition is an object that MUST contain the following member: • Name— A string Reference values to a metric Target members. Metric targets MUST be either a numeric value or an array of numeric values. Specification: Embedded metric format 2780 Amazon CloudWatch User Guide A MetricDefinition object MAY contain the following members: • Unit— An OPTIONAL string value representing the unit of measure for the corresponding metric. Values SHOULD be valid CloudWatch metric units. For information about valid units, see MetricDatum. If a value is not provided, then a default value of NONE is assumed. • StorageResolution— An OPTIONAL integer value representing the storage resolution for the corresponding metric. Setting this to 1 specifies this metric as a high-resolution metric, so that CloudWatch stores the metric with sub-minute resolution down to one second. Setting this to 60 specifies this metric as standard-resolution, which CloudWatch stores at 1-minute resolution. Values SHOULD be valid CloudWatch supported resolutions, 1 or 60. If a value is not provided, then a default value of 60 is assumed. For more information about high-resolution metrics, see High-resolution metrics. Note If you plan to create alarms on metrics created using embedded metric format, see Setting alarms on metrics created with the embedded metric format for recommendations. { "_aws": { "CloudWatchMetrics": [ { "Metrics": [ { "Name": "Time", "Unit": "Milliseconds", "StorageResolution": 60 } ], ... } ] }, "Time": 1 } Specification: Embedded metric format 2781 Amazon CloudWatch Reference values User Guide Reference values are string values that reference Target members members on the root node. These references should NOT be confused with the JSON Pointers described in RFC6901. Target values cannot be nested. Target members Valid targets MUST be members on the root node and cannot be nested objects. For example, a _reference_ value of "A.a" MUST match the following member: { "A.a" } It MUST NOT match the nested member: { "A": { "a" } } Valid values of target members depend on what is referencing them. A metric target MUST be a numeric value or an array of numeric values. Numeric array metric targets MUST NOT have more than 100 members. A dimension target MUST have a string value. Embedded metric format example and JSON schema The following is a valid example of embedded metric format. { "_aws": { "Timestamp": 1574109732004, "CloudWatchMetrics": [ { "Namespace": "lambda-function-metrics", "Dimensions": [["functionVersion"]], "Metrics": [ { "Name": "time", "Unit": "Milliseconds", "StorageResolution": 60 } ] } ] Specification: Embedded metric format 2782 Amazon CloudWatch }, "functionVersion": "$LATEST", "time": 100, "requestId": "989ffbf8-9ace-4817-a57c-e4dd734019ee" } User Guide You can use the following schema to validate embedded metric format documents. { "type": "object", "title": "Root Node", "required": [ "_aws" ], "properties": { "_aws": { "$id": "#/properties/_aws", "type": "object", "title": "Metadata", "required": [ "Timestamp", "CloudWatchMetrics" ], "properties": { "Timestamp": { "$id": "#/properties/_aws/properties/Timestamp", "type": "integer", "title": "The Timestamp Schema", "examples": [ 1565375354953 ] }, "CloudWatchMetrics": { "$id": "#/properties/_aws/properties/CloudWatchMetrics", "type": "array", "title": "MetricDirectives", "items": { "$id": "#/properties/_aws/properties/CloudWatchMetrics/items", "type": "object", "title": "MetricDirective", "required": [ "Namespace", "Dimensions", Specification: Embedded metric format 2783 Amazon CloudWatch User Guide "Metrics" ], "properties": { "Namespace": { "$id": "#/properties/_aws/properties/CloudWatchMetrics/ items/properties/Namespace", "type": "string", "title": "CloudWatch Metrics Namespace", "examples": [ "MyApp" ], "pattern": "^(.*)$", "minLength": 1, "maxLength": 1024 }, "Dimensions": { "$id": "#/properties/_aws/properties/CloudWatchMetrics/ items/properties/Dimensions", "type": "array", "title": "The Dimensions Schema", "minItems": 1, "items": { "$id": "#/properties/_aws/properties/ CloudWatchMetrics/items/properties/Dimensions/items", "type": "array", "title": "DimensionSet", "minItems": 0, "maxItems": 30, "items": { "$id": "#/properties/_aws/properties/ CloudWatchMetrics/items/properties/Dimensions/items/items", "type": "string", "title": "DimensionReference", "examples": [
acw-ug-799
acw-ug.pdf
799
"The Timestamp Schema", "examples": [ 1565375354953 ] }, "CloudWatchMetrics": { "$id": "#/properties/_aws/properties/CloudWatchMetrics", "type": "array", "title": "MetricDirectives", "items": { "$id": "#/properties/_aws/properties/CloudWatchMetrics/items", "type": "object", "title": "MetricDirective", "required": [ "Namespace", "Dimensions", Specification: Embedded metric format 2783 Amazon CloudWatch User Guide "Metrics" ], "properties": { "Namespace": { "$id": "#/properties/_aws/properties/CloudWatchMetrics/ items/properties/Namespace", "type": "string", "title": "CloudWatch Metrics Namespace", "examples": [ "MyApp" ], "pattern": "^(.*)$", "minLength": 1, "maxLength": 1024 }, "Dimensions": { "$id": "#/properties/_aws/properties/CloudWatchMetrics/ items/properties/Dimensions", "type": "array", "title": "The Dimensions Schema", "minItems": 1, "items": { "$id": "#/properties/_aws/properties/ CloudWatchMetrics/items/properties/Dimensions/items", "type": "array", "title": "DimensionSet", "minItems": 0, "maxItems": 30, "items": { "$id": "#/properties/_aws/properties/ CloudWatchMetrics/items/properties/Dimensions/items/items", "type": "string", "title": "DimensionReference", "examples": [ "Operation" ], "pattern": "^(.*)$", "minLength": 1, "maxLength": 250 } } }, "Metrics": { Specification: Embedded metric format 2784 Amazon CloudWatch User Guide "$id": "#/properties/_aws/properties/CloudWatchMetrics/ items/properties/Metrics", "type": "array", "title": "MetricDefinitions", "items": { "$id": "#/properties/_aws/properties/ CloudWatchMetrics/items/properties/Metrics/items", "type": "object", "title": "MetricDefinition", "required": [ "Name" ], "properties": { "Name": { "$id": "#/properties/_aws/properties/ CloudWatchMetrics/items/properties/Metrics/items/properties/Name", "type": "string", "title": "MetricName", "examples": [ "ProcessingLatency" ], "pattern": "^(.*)$", "minLength": 1, "maxLength": 1024 }, "Unit": { "$id": "#/properties/_aws/properties/ CloudWatchMetrics/items/properties/Metrics/items/properties/Unit", "type": "string", "title": "MetricUnit", "examples": [ "Milliseconds" ], "pattern": "^(Seconds|Microseconds| Milliseconds|Bytes|Kilobytes|Megabytes|Gigabytes|Terabytes|Bits|Kilobits|Megabits| Gigabits|Terabits|Percent|Count|Bytes\\/Second|Kilobytes\\/Second|Megabytes\\/Second| Gigabytes\\/Second|Terabytes\\/Second|Bits\\/Second|Kilobits\\/Second|Megabits\\/ Second|Gigabits\\/Second|Terabits\\/Second|Count\\/Second|None)$" }, "StorageResolution": { "$id": "#/properties/_aws/properties/ CloudWatchMetrics/items/properties/Metrics/items/properties/StorageResolution", "type": "integer", "title": "StorageResolution", Specification: Embedded metric format 2785 Amazon CloudWatch User Guide "examples": [ 60 ] } } } } } } } } } } } Using the PutLogEvents API to send manually-created embedded metric format logs You can send embedded metric format logs to CloudWatch Logs using the CloudWatch Logs PutLogEvents API. When calling PutLogEvents, you have the option to include the following HTTP header, which tells CloudWatch Logs the metrics should be extracted, but it's not required. x-amzn-logs-format: json/emf The following is a full example using the AWS SDK for Java 2.x: package org.example.basicapp; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse; import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent; import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest; import java.util.Collections; public class EmbeddedMetricsExample { public static void main(String[] args) { final String usage = "To run this example, supply a Region code (eg. us-east-1), log group, and stream name as command line arguments" Using the PutLogEvents API to send manually-created embedded metric format logs 2786 Amazon CloudWatch User Guide + "Ex: PutLogEvents <region-id> <log-group-name> <stream-name>"; if (args.length != 3) { System.out.println(usage); System.exit(1); } String regionId = args[0]; String logGroupName = args[1]; String logStreamName = args[2]; CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder().region(Region.of(regionId)).build(); // Build a JSON log using the EmbeddedMetricFormat. long timestamp = System.currentTimeMillis(); String message = "{" + " \"_aws\": {" + " \"Timestamp\": " + timestamp + "," + " \"CloudWatchMetrics\": [" + " {" + " \"Namespace\": \"MyApp\"," + " \"Dimensions\": [[\"Operation\"], [\"Operation \", \"Cell\"]]," + " \"Metrics\": [{ \"Name\": \"ProcessingLatency \", \"Unit\": \"Milliseconds\", \"StorageResolution\": 60 }]" + " }" + " ]" + " }," + " \"Operation\": \"Aggregator\"," + " \"Cell\": \"001\"," + " \"ProcessingLatency\": 100" + "}"; InputLogEvent inputLogEvent = InputLogEvent.builder() .message(message) .timestamp(timestamp) .build(); // Specify the request parameters. PutLogEventsRequest putLogEventsRequest = PutLogEventsRequest.builder() .logEvents(Collections.singletonList(inputLogEvent)) .logGroupName(logGroupName) .logStreamName(logStreamName) Using the PutLogEvents API to send manually-created embedded metric format logs 2787 Amazon CloudWatch User Guide .build(); logsClient.putLogEvents(putLogEventsRequest); System.out.println("Successfully put CloudWatch log event"); } } Note With the embedded metric format, you can track the processing of your EMF logs by metrics that are published in the AWS/Logs namespace of your account. These can be used to track failed metric generation from EMF, as well as whether failures happen due to parsing or validation. For more details see Monitoring with CloudWatch metrics. Using the CloudWatch agent to send embedded metric format logs This section describes how to install and use the CloudWatch agent. The first part of this section describes how to install the CloudWatch agent. The the second part of this section describes how to use the CloudWatch agent to send embedded metric format logs. If you want to use this method, you must install the CloudWatch agent for the AWS services you want to send embedded metric format logs from. Then you can begin sending the events. The CloudWatch agent must be version 1.230621.0 or later. Note You do not need to install the CloudWatch agent to send logs from Lambda functions. Lambda function timeouts are not handled automatically. This means that if your function times out before the metrics get flushed, then the metrics for that invocation will not be captured. Installing the CloudWatch agent Install the CloudWatch agent for each service which is to send embedded metric format logs. Using the CloudWatch agent to send embedded metric format logs 2788 Amazon CloudWatch User Guide Installing the CloudWatch agent on EC2 First, install the CloudWatch agent on the instance. For more information, see Install the CloudWatch agent. Once you have installed the agent, configure the agent to listen on a UDP or TCP port for the embedded metric format logs. The following is an example of this configuration that listens on the default socket tcp:25888. For more
acw-ug-800
acw-ug.pdf
800
will not be captured. Installing the CloudWatch agent Install the CloudWatch agent for each service which is to send embedded metric format logs. Using the CloudWatch agent to send embedded metric format logs 2788 Amazon CloudWatch User Guide Installing the CloudWatch agent on EC2 First, install the CloudWatch agent on the instance. For more information, see Install the CloudWatch agent. Once you have installed the agent, configure the agent to listen on a UDP or TCP port for the embedded metric format logs. The following is an example of this configuration that listens on the default socket tcp:25888. For more information about agent configuration, see Manually create or edit the CloudWatch agent configuration file. { "logs": { "metrics_collected": { "emf": { } } } } Installing the CloudWatch agent on Amazon ECS The easiest way to deploy the CloudWatch agent on Amazon ECS is to run it as a sidecar, defining it in the same task definition as your application. Create agent configuration file Create your CloudWatch agent configuration file locally. In this example, the relative file path will be amazon-cloudwatch-agent.json. For more information about agent configuration, see Manually create or edit the CloudWatch agent configuration file. { "logs": { "metrics_collected": { "emf": { } } } } Push configuration to SSM Parameter Store Using the CloudWatch agent to send embedded metric format logs 2789 Amazon CloudWatch User Guide Enter the following command to push the CloudWatch agent configuration file to the AWS Systems Manager (SSM) Parameter Store. aws ssm put-parameter \ --name "cwagentconfig" \ --type "String" \ --value "`cat amazon-cloudwatch-agent.json`" \ --region "{{region}}" Configure the task definition Configure your task definition to use the CloudWatch Agent and expose the TCP or UDP port. The sample task definition that you should use depends on your networking mode. Notice that the webapp specifies the AWS_EMF_AGENT_ENDPOINT environment variable. This is used by the library and should point to the endpoint that the agent is listening on. Additionally, the cwagent specifies the CW_CONFIG_CONTENT as a “valueFrom” parameter that points to the SSM configuration that you created in the previous step. This section contains one example for bridge mode and one example for host or awsvpc mode. For more examples of how you can configure the CloudWatch agent on Amazon ECS, see the Github samples repository The following is an example for bridge mode. When bridge mode networking is enabled, the agent needs to be linked to your application using the links parameter and must be addressed using the container name. { "containerDefinitions": [ { "name": "webapp", "links": [ "cwagent" ], "image": "my-org/web-app:latest", "memory": 256, "cpu": 256, "environment": [{ "name": "AWS_EMF_AGENT_ENDPOINT", "value": "tcp://cwagent:25888" }], }, { Using the CloudWatch agent to send embedded metric format logs 2790 Amazon CloudWatch User Guide "name": "cwagent", "mountPoints": [], "image": "public.ecr.aws/cloudwatch-agent/cloudwatch-agent:latest", "memory": 256, "cpu": 256, "portMappings": [{ "protocol": "tcp", "containerPort": 25888 }], "environment": [{ "name": "CW_CONFIG_CONTENT", "valueFrom": "cwagentconfig" }], } ], } The following is an example for host mode or awsvpc mode. When running on these network modes, the agent can be addressed over localhost. { "containerDefinitions": [ { "name": "webapp", "image": "my-org/web-app:latest", "memory": 256, "cpu": 256, "environment": [{ "name": "AWS_EMF_AGENT_ENDPOINT", "value": "tcp://127.0.0.1:25888" }], }, { "name": "cwagent", "mountPoints": [], "image": "public.ecr.aws/cloudwatch-agent/cloudwatch-agent:latest", "memory": 256, "cpu": 256, "portMappings": [{ "protocol": "tcp", "containerPort": 25888 }], "environment": [{ Using the CloudWatch agent to send embedded metric format logs 2791 Amazon CloudWatch User Guide "name": "CW_CONFIG_CONTENT", "valueFrom": "cwagentconfig" }], } ], } Note In awsvpc mode, you must either give a public IP address to the VPC (Fargate only), set up a NAT gateway, or set up a CloudWatch Logs VPC endpoint. For more information about setting up a NAT, see NAT Gateways. For more information about setting up a CloudWatch Logs VPC endpoint, see Using CloudWatch Logs with Interface VPC Endpoints. The following is an example of how to assign a public IP address to a task that uses the Fargate launch type. aws ecs run-task \ --cluster {{cluster-name}} \ --task-definition cwagent-fargate \ --region {{region}} \ --launch-type FARGATE \ --network-configuration "awsvpcConfiguration={subnets=[{{subnetId}}],securityGroups=[{{sgId}}],assignPublicIp=ENABLED}" Ensure permissions Ensure the IAM role executing your tasks has permission to read from the SSM Parameter Store. You can add this permission by attaching the AmazonSSMReadOnlyAccess policy. To do so, enter the following command. aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess \ --role-name CWAgentECSExecutionRole Installing the CloudWatch agent on Amazon EKS Parts of this process can be skipped if you have already installed CloudWatch Container Insights on this cluster. Using the CloudWatch agent to send embedded metric format logs 2792 Amazon CloudWatch Permissions User Guide If you have not already installed Container Insights, then first ensure that your Amazon EKS nodes have the appropriate IAM permissions. They should have the CloudWatchAgentServerPolicy attached. For more information, see Verifying prerequisites for Container Insights in CloudWatch. Create ConfigMap Create a ConfigMap for the
acw-ug-801
acw-ug.pdf
801
do so, enter the following command. aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess \ --role-name CWAgentECSExecutionRole Installing the CloudWatch agent on Amazon EKS Parts of this process can be skipped if you have already installed CloudWatch Container Insights on this cluster. Using the CloudWatch agent to send embedded metric format logs 2792 Amazon CloudWatch Permissions User Guide If you have not already installed Container Insights, then first ensure that your Amazon EKS nodes have the appropriate IAM permissions. They should have the CloudWatchAgentServerPolicy attached. For more information, see Verifying prerequisites for Container Insights in CloudWatch. Create ConfigMap Create a ConfigMap for the agent. The ConfigMap also tells the agent to listen on a TCP or UDP port. Use the following ConfigMap. # cwagent-emf-configmap.yaml apiVersion: v1 data: # Any changes here must not break the JSON format cwagentconfig.json: | { "agent": { "omit_hostname": true }, "logs": { "metrics_collected": { "emf": { } } } } kind: ConfigMap metadata: name: cwagentemfconfig namespace: default If you have already installed Container Insights, add the following "emf": { } line to your existing ConfigMap. Apply the ConfigMap Enter the following command to apply the ConfigMap. kubectl apply -f cwagent-emf-configmap.yaml Deploy the agent Using the CloudWatch agent to send embedded metric format logs 2793 Amazon CloudWatch User Guide To deploy the CloudWatch agent as a sidecar, add the agent to your pod definition, as in the following example. apiVersion: v1 kind: Pod metadata: name: myapp namespace: default spec: containers: # Your container definitions go here - name: web-app image: my-org/web-app:latest # CloudWatch Agent configuration - name: cloudwatch-agent image: public.ecr.aws/cloudwatch-agent/cloudwatch-agent:latest imagePullPolicy: Always resources: limits: cpu: 200m memory: 100Mi requests: cpu: 200m memory: 100Mi volumeMounts: - name: cwagentconfig mountPath: /etc/cwagentconfig ports: # this should match the port configured in the ConfigMap - protocol: TCP hostPort: 25888 containerPort: 25888 volumes: - name: cwagentconfig configMap: name: cwagentemfconfig Using the CloudWatch agent to send embedded metric format logs When you have the CloudWatch agent installed and running, you can send the embedded metric format logs over TCP or UDP. There are two requirements when sending the logs over the agent: • The logs must contain a LogGroupName key that tells the agent which log group to use. Using the CloudWatch agent to send embedded metric format logs 2794 Amazon CloudWatch User Guide • Each log event must be on a single line. In other words, a log event cannot contain the newline (\n) character. The log events must also follow the embedded metric format specification. For more information, see Specification: Embedded metric format. If you plan to create alarms on metrics created using embedded metric format, see Setting alarms on metrics created with the embedded metric format for recommendations. The following is an example of sending log events manually from a Linux bash shell. You can instead use the UDP socket interfaces provided by your programming language of choice. echo '{"_aws":{"Timestamp":1574109732004,"LogGroupName":"Foo","CloudWatchMetrics": [{"Namespace":"MyApp","Dimensions":[["Operation"]],"Metrics": [{"Name":"ProcessingLatency","Unit":"Milliseconds","StorageResolution":60}]}]},"Operation":"Aggregator","ProcessingLatency":100}' \ > /dev/udp/0.0.0.0/25888 Note With the embedded metric format, you can track the processing of your EMF logs by metrics that are published in the AWS/Logs namespace of your account. These can be used to track failed metric generation from EMF, as well as whether failures happen due to parsing or validation. For more details see Monitoring with CloudWatch metrics. Using the embedded metric format with AWS Distro for OpenTelemetry OpenTelemetry is an open-source initiative that removes boundaries and restrictions between vendor-specific formats for tracing, logs, and metrics by offering a single set of specifications and APIs. For more information, see OpenTelemetry. You can use the embedded metric format as a part of the OpenTelemetry project. Using the embedded metric format with OpenTelemetry requires two components: an OpenTelemetry-compliant data source and the AWS Distro for OpenTelemetry Collector enabled for use with CloudWatch embedded metric format logs. We have preconfigured redistributions of the OpenTelemetry components, which AWS maintains, to make onboarding as easy as possible. For more information about using OpenTelemetry with the embedded metric format, in addition to other AWS services, see AWS Distro for Using the embedded metric format with AWS Distro for OpenTelemetry 2795 Amazon CloudWatch User Guide OpenTelemetry. For additional information regarding language support and usage, see AWS Observability on Github. Viewing your metrics and logs in the console After you generate embedded metric format logs that extract metrics, you can use the CloudWatch console to view the metrics. Embedded metrics have the dimensions that you specified when you generated the logs. Also, the embedded metrics that you generated using the client libraries have the following default dimensions: • ServiceType • ServiceName • LogGroup This section describes how to view these metrics in the CloudWatch console and query your extracted metrics using CloudWatch Logs Insights. To view metrics that were generated from embedded metric format logs 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. 3. 4. 5.
acw-ug-802
acw-ug.pdf
802
the console After you generate embedded metric format logs that extract metrics, you can use the CloudWatch console to view the metrics. Embedded metrics have the dimensions that you specified when you generated the logs. Also, the embedded metrics that you generated using the client libraries have the following default dimensions: • ServiceType • ServiceName • LogGroup This section describes how to view these metrics in the CloudWatch console and query your extracted metrics using CloudWatch Logs Insights. To view metrics that were generated from embedded metric format logs 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. 3. 4. 5. In the navigation pane, choose Metrics. Select a namespace that you specified for your embedded metrics when you generated them. If you used the client libraries to generate the metrics and did not specify a namespace, then select aws-embedded-metrics. This is the default namespace for embedded metrics generated using the client libraries. Select a metric dimension (for example, ServiceName). The All metrics tab displays all metrics for that dimension in the namespace. You can do the following: a. b. c. d. To sort the table, use the column heading. To graph a metric, select the check box next to the metric. To select all metrics, select the check box in the heading row of the table. To filter by resource, choose the resource ID and then choose Add to search. To filter by metric, choose the metric name and then choose Add to search. Querying logs using CloudWatch Logs Insights Viewing your metrics and logs in the console 2796 Amazon CloudWatch User Guide You can query the detailed log events associated with the extracted metrics by using CloudWatch Logs Insights to provide deep insights into the root causes of operational events. One of the benefits of extracting metrics from your logs is that you can filter your logs later by the unique metric (metric name plus unique dimension set) and metric values, to get context on the events that contributed to the aggregated metric value For example, to get an impacted request id or x-ray trace id, you could run the following query in CloudWatch Logs Insights. filter Latency > 1000 and Operation = "Aggregator" | fields RequestId, TraceId You can also perform query-time aggregation on high-cardinality keys, such as finding the customers impacted by an event. The following example illustrates this. filter Latency > 1000 and Operation = "Aggregator" | stats count() by CustomerId For more information, see Analyzing Log Data with CloudWatch Logs Insights Setting alarms on metrics created with the embedded metric format In general, creating alarms on metrics generated by the embedded metric format follows the same pattern as creating alarms on any other metrics. For more information, see Using Amazon CloudWatch alarms. Embedded metric format metric generation depends on your log publishing flow because CloudWatch Logs needs to process logs so they can be transformed into metrics. It’s important to publish logs in a timely manner, so that metric datapoints are created within the period of time that alarms are evaluated. If you plan on using the embedded metric format to send high-resolution metrics and create alarms on these metrics, we recommended that you flush logs to CloudWatch Logs at an interval of 5 seconds or less to avoid introducing an additional delay, which can cause alarming on partial or missing data. If you are using the CloudWatch agent, you can adjust the flush interval by setting the force_flush_interval parameter in the CloudWatch agent configuration file. This value defaults to 5 seconds. If you are using Lambda on other platforms where you can’t control the log flush interval, consider using “M out of N” alarms to control the number of datapoints used to alarm. For more information, see Evaluating an alarm. Setting alarms on metrics created with the embedded metric format 2797 Amazon CloudWatch User Guide AWS services that publish CloudWatch metrics You can use the following table to learn which AWS services publish metrics to CloudWatch. For information about the metrics and dimensions, see the specified documentation. Service Namespace Documentation AWS Amplify AWS/Ampli Monitoring fyHosting Amazon API Gateway Amazon AppFlow AWS Applicati on Migration Service AWS/ApiGa Monitor API Execution with Amazon CloudWatch teway AWS/AppFlow Monitoring Amazon AppFlow with Amazon CloudWatch AWS/MGN Monitoring Application Migration Service with Amazon CloudWatch AWS App Runner AWS/AppRu nner Viewing App Runner service metrics reported to CloudWatch AppStream 2.0 AWS/AppSt Monitoring Amazon AppStream 2.0 Resources ream AWS AppSync AWS/AppSync CloudWatch Metrics Amazon Athena AWS/Athena Monitoring Athena Queries with CloudWatch Metrics Amazon Aurora AWS/RDS Amazon Aurora metrics AWS Backup AWS/Backup Monitoring AWS Backup Metrics with CloudWatch Amazon Bedrock Guardrails AWS/Bedro ck/Guardr Monitoring Amazon Bedrock Guardrails using CloudWatc h Metrics ails 2798 Amazon CloudWatch User Guide Service Namespace Documentation AWS Billing and Cost Management AWS/Billing Monitoring Charges with Alerts and Notifications Amazon
acw-ug-803
acw-ug.pdf
803
Monitoring Amazon AppFlow with Amazon CloudWatch AWS/MGN Monitoring Application Migration Service with Amazon CloudWatch AWS App Runner AWS/AppRu nner Viewing App Runner service metrics reported to CloudWatch AppStream 2.0 AWS/AppSt Monitoring Amazon AppStream 2.0 Resources ream AWS AppSync AWS/AppSync CloudWatch Metrics Amazon Athena AWS/Athena Monitoring Athena Queries with CloudWatch Metrics Amazon Aurora AWS/RDS Amazon Aurora metrics AWS Backup AWS/Backup Monitoring AWS Backup Metrics with CloudWatch Amazon Bedrock Guardrails AWS/Bedro ck/Guardr Monitoring Amazon Bedrock Guardrails using CloudWatc h Metrics ails 2798 Amazon CloudWatch User Guide Service Namespace Documentation AWS Billing and Cost Management AWS/Billing Monitoring Charges with Alerts and Notifications Amazon Braket AWS/Braket/ Monitoring Amazon Braket with Amazon CloudWatch By Device AWS Certificate Manager AWS/Certi ficateMan ager Supported CloudWatch Metrics AWS Private CA AWS/ACMPr Supported CloudWatch Metrics ivateCA AWS/Chatbot Amazon Q Developer in chat applications Monitoring Amazon Q Developer in chat applications with Amazon CloudWatch Amazon Chime AWS/Chime Monitoring Amazon Chime with Amazon CloudWatch VoiceConn ector Amazon Chime SDK AWS/Chime Service metrics SDK AWS Client VPN AWS/Clien Monitoring with Amazon CloudWatch tVPN Amazon CloudFront AWS/Cloud Monitoring CloudFront Activity Using CloudWatch Front AWS CloudHSM AWS/Cloud Getting CloudWatch Metrics HSM Amazon CloudSearch AWS/Cloud Search Monitoring an Amazon CloudSearch Domain with Amazon CloudWatch 2799 Amazon CloudWatch User Guide Service Namespace Documentation AWS CloudTrail AWS/Cloud Supported CloudWatch metrics Trail CWAgent or a custom namespace Applicati onSignals AWS/Cloud Watch/Met ricStreams AWS/RUM CloudWatc hSyntheti cs Metrics collected by the CloudWatch agent Metrics collected by Application Signals Monitoring your metric streams with CloudWatch metrics CloudWatch metrics that you can collect with CloudWatc h RUM CloudWatch metrics published by canaries AWS/Logs Monitoring Usage with CloudWatch Metrics CloudWatch agent CloudWatch Application Signals CloudWatch metric streams CloudWatch RUM CloudWatch Synthetics Amazon CloudWatch Logs AWS CodeBuild AWS/CodeB Monitoring AWS CodeBuild uild Amazon CodeGuru Reviewer AWS CodePipel ine Monitoring CodeGuru Reviewer with Amazon CloudWatc h AWS CodePipeline CloudWatch metrics Amazon Kendra Monitoring Amazon Kendra with Amazon CloudWatch 2800 Amazon CloudWatch User Guide Service Namespace Documentation Amazon Cognito AWS/Cognito Monitoring Amazon Cognito Amazon Comprehend AWS/Compr Monitoring Amazon Comprehend endpoints ehend AWS Config AWS/Config AWS Config Usage and Success Metrics Amazon Connect AWS/Connect Monitoring Amazon Connect in Amazon CloudWatch Metrics Amazon Data Lifecycle Manager AWS/DataL ifecycleM anager Monitor your policies using Amazon CloudWatch AWS DataSync AWS/DataS Monitoring Your Task ync Amazon DataZone Monitoring Amazon DataZone with Amazon CloudWatch Amazon DevOps Guru AWS/DevOps- Guru Monitoring Amazon DevOps Guru with Amazon CloudWatch AWS Database Migration Service AWS Direct Connect AWS/DMS Monitoring AWS DMS Tasks AWS/DX Monitoring with Amazon CloudWatch AWS Directory Service AWS/Direc toryServi Use Amazon CloudWatch metrics to determine when to add domain controllers ce Amazon DocumentDB AWS/DocDB Monitoring Amazon DocumentDB with CloudWatch 2801 Amazon CloudWatch User Guide Service Namespace Documentation Amazon DynamoDB DynamoDB Accelerator (DAX) AWS/Dynam DynamoDB Metrics and Dimensions oDB AWS/DAX Viewing DAX Metrics and Dimensions Amazon EC2 AWS/EC2 Monitoring Your Instances Using CloudWatch Amazon EC2 Elastic Graphics Amazon EC2 Spot Fleet AWS/Elast Using CloudWatch metrics to monitor Elastic Graphics icGPUs AWS/EC2Spot CloudWatch Metrics for Spot Fleet Amazon EC2 Auto Scaling AWS/AutoS caling Monitoring Your Auto Scaling Groups and Instances Using CloudWatch AWS Elastic Beanstalk AWS/Elast icBeansta lk Publishing Amazon CloudWatch Custom Metrics for an Environment Amazon Elastic Block Store Amazon Elastic Container Registry Amazon Elastic Container Service AWS/EBS Amazon CloudWatch Metrics for Amazon EBS AWS/ECR Amazon ECR repository metrics AWS/ECS Amazon ECS CloudWatch Metrics 2802 Amazon CloudWatch User Guide Service Namespace Documentation Amazon ECS through CloudWatc h Container Insights Amazon ECS Cluster auto scaling AWS Elastic Disaster Recovery Amazon Elastic File System ECS/Conta inerInsig hts AWS/ECS/M anagedSca ling Amazon ECS Container Insights metrics Amazon ECS cluster auto scaling CloudWatch Metrics for DRS AWS/EFS Monitoring with CloudWatch Amazon Elastic Inference AWS/Elast icInferen Using CloudWatch Metrics to Monitor Amazon Elastic Inference ce Amazon EKS AWS/EKS Basic metrics in Amazon CloudWatch Amazon EKS through CloudWatc h Container Insights Elastic Load Balancing Elastic Load Balancing Elastic Load Balancing Container Amazon EKS and Kubernetes Container Insights metrics Insights AWS/Appli cationELB CloudWatch Metrics for your Application Load Balancer AWS/Netwo CloudWatch Metrics for your Network Load Balancer rkELB AWS/Gatew CloudWatch Metrics for your Gateway Load Balancer ayELB 2803 Amazon CloudWatch User Guide Service Namespace Documentation Elastic Load Balancing AWS/ELB CloudWatch Metrics for your Classic Load Balancer Amazon Elastic Transcoder AWS/Elast icTransco der Monitoring with Amazon CloudWatch Amazon ElastiCache (Memcached) Amazon ElastiCache (Redis OSS) Amazon OpenSearch Service Amazon EMR AWS/Elast Monitoring Use with CloudWatch Metrics iCache AWS/Elast Monitoring Use with CloudWatch Metrics iCache AWS/ES AWS/Elast icMapRedu ce Monitoring OpenSearch cluster metrics with Amazon CloudWatch Monitor Metrics with CloudWatch AWS Elemental MediaConnect AWS/Media Monitoring MediaConnect with Amazon CloudWatch Connect AWS Elemental MediaConvert AWS/Media Convert Using CloudWatch Metrics to View Metrics for AWS Elemental MediaConvert Resources AWS Elemental MediaLive AWS/Media Monitoring activity using Amazon CloudWatch metrics Live AWS Elemental MediaPackage AWS/Media Package Monitoring AWS Elemental MediaPackage with Amazon CloudWatch Metrics AWS Elemental MediaStore
acw-ug-804
acw-ug.pdf
804
icTransco der Monitoring with Amazon CloudWatch Amazon ElastiCache (Memcached) Amazon ElastiCache (Redis OSS) Amazon OpenSearch Service Amazon EMR AWS/Elast Monitoring Use with CloudWatch Metrics iCache AWS/Elast Monitoring Use with CloudWatch Metrics iCache AWS/ES AWS/Elast icMapRedu ce Monitoring OpenSearch cluster metrics with Amazon CloudWatch Monitor Metrics with CloudWatch AWS Elemental MediaConnect AWS/Media Monitoring MediaConnect with Amazon CloudWatch Connect AWS Elemental MediaConvert AWS/Media Convert Using CloudWatch Metrics to View Metrics for AWS Elemental MediaConvert Resources AWS Elemental MediaLive AWS/Media Monitoring activity using Amazon CloudWatch metrics Live AWS Elemental MediaPackage AWS/Media Package Monitoring AWS Elemental MediaPackage with Amazon CloudWatch Metrics AWS Elemental MediaStore AWS/Media Store Monitoring AWS Elemental MediaStore with Amazon CloudWatch Metrics 2804 Amazon CloudWatch User Guide Service Namespace Documentation AWS Elemental MediaTailor AWS/Media Tailor Monitoring AWS Elemental MediaTailor with Amazon CloudWatch AWS End User Messaging SMS AWS/SMSVo ice Monitoring AWS End User Messaging SMS with Amazon CloudWatch AWS End User Messaging Social AWS/Socia lMessaging Monitoring AWS End User Messaging Social with Amazon CloudWatch Amazon EventBridge Amazon FinSpace Amazon Forecast Amazon Fraud Detector Amazon FSx for Lustre Amazon FSx for OpenZFS Amazon FSx for Windows File Server Amazon FSx for NetApp ONTAP Amazon FSx for OpenZFS AWS/Events Monitoring Amazon EventBridge Logging and monitoring CloudWatch Metrics for Amazon Forecast Monitoring Amazon Fraud Detector with Amazon CloudWatch AWS/FSx Monitoring Amazon FSx for Lustre AWS/FSx Monitoring with Amazon CloudWatch AWS/FSx Monitoring Amazon FSx for Windows File Server AWS/FSx Monitoring with Amazon CloudWatch AWS/FSx Monitoring with Amazon CloudWatch 2805 Amazon CloudWatch User Guide Service Namespace Documentation Amazon GameLift Servers AWS/GameL Monitor Amazon GameLift Servers with CloudWatch ift AWS Global Accelerator AWS/Globa lAccelera Using Amazon CloudWatch with AWS Global Accelerator AWS Glue AWS Ground Station tor Glue Monitoring AWS Glue Using CloudWatch Metrics AWS/Groun Metrics Using Amazon CloudWatch dStation AWS HealthLake AWS/Healt Monitoring HealthLake with CloudWatch hLake Amazon Inspector Amazon Interactive Video Service Amazon Interactive Video Service Chat AWS/Inspe Monitoring Amazon Inspector Using CloudWatch ctor AWS/IVS Monitoring Amazon IVS with Amazon CloudWatch AWS/IVSChat Monitoring Amazon IVS with Amazon CloudWatch AWS IoT AWS/IoT AWS IoT Metrics and Dimensions AWS IoT Analytics AWS IoT FleetWise AWS IoT SiteWise AWS/IoTAn Namespace, Metrics, and Dimensions alytics AWS/IoTFl Monitoring AWS IoT FleetWise with Amazon CloudWatch eetWise AWS/IoTSi teWise Monitoring AWS IoT SiteWise with Amazon CloudWatch metrics 2806 Amazon CloudWatch User Guide Service Namespace Documentation AWS IoT TwinMaker AWS/IoTTw inMaker Monitoring AWS IoT TwinMaker with Amazon CloudWatc h metrics AWS Key Management Service Amazon Keyspaces (for Apache Cassandra) AWS/KMS Monitoring with CloudWatch AWS/Cassa Amazon Keyspaces Metrics and Dimensions ndra Amazon Kendra Monitoring Amazon Kendra with Amazon CloudWatch Amazon Managed Service AWS/Kines isAnalyti Managed Service for Apache Flink for SQL Applications: Monitoring with CloudWatch for Apache Flink cs Managed Service for Apache Flink for Apache Flink: Viewing Amazon Managed Service for Apache Flink Metrics and Dimensions Amazon Data Firehose Amazon Kinesis Data Streams AWS/Fireh Monitoring Firehose Using CloudWatch Metrics ose AWS/Kinesis Monitoring Amazon Kinesis Data Streams with Amazon CloudWatch Amazon Kinesis Video Streams AWS/Kines isVideo Monitoring Kinesis Video Streams Metrics with CloudWatch AWS Lambda AWS/Lambda AWS Lambda Metrics Amazon Lex AWS/Lex Monitoring Amazon Lex with Amazon CloudWatch 2807 Amazon CloudWatch User Guide Service Namespace Documentation Monitoring license usage with Amazon CloudWatch Usage metrics and Amazon CloudWatch alarms for Linux subscriptions AWS License Manager AWSLicens eManager/ licenseUs age AWS/Licen seManager /LinuxSub scriptions Amazon Location Service AWS/Locat ion Amazon Location Service metrics exported to Amazon CloudWatch Amazon Lookout for Equipment AWS/looko utequipme Monitoring Lookout for Equipment with Amazon CloudWatch nt Amazon Lookout for Metrics AWS/Looko utMetrics Monitoring Lookout for Metrics with Amazon CloudWatc h Amazon Lookout for Vision AWS/Looko utVision Monitoring Lookout for Vision with Amazon CloudWatch AWS Mainframe Modernization Monitoring AWS Mainframe Modernization with Amazon CloudWatch Amazon Machine Learning Amazon Managed Blockchain AWS/ML Monitoring Amazon ML with CloudWatch Metrics AWS/manag edblockch ain Use Hyperledger Fabric Peer Node Metrics on Amazon Managed Blockchain Amazon Managed Service for Prometheus AWS/Prome Amazon CloudWatch metrics theus 2808 Amazon CloudWatch User Guide Service Namespace Documentation Amazon Managed Streaming for Apache Kafka Amazon Managed Streaming for Apache Kafka Amazon Managed Workflows for Apache Airflow Amazon MemoryDB AWS/Kafka Monitoring Amazon MSK with Amazon CloudWatch AWS/Kafka Monitoring MSK Connect Connect AWS/MWAA Container, queue, and database metrics for Amazon MWAA AWS/Memor Monitoring CloudWatch metrics yDB Amazon MQ AWS/Amazo nMQ Monitoring Amazon MQ Brokers Using Amazon CloudWatch Amazon Neptune AWS/Neptune Monitoring Neptune with CloudWatch AWS Network Firewall AWS/Netwo rkFirewall AWS Network Manager AWS/Netwo rkManager AWS Network Firewall metrics in Amazon CloudWatch CloudWatch metrics for on-premises resources AWS HealthOmi cs AWS/Omics Monitoring AWS HealthOmics with Amazon CloudWatch AWS OpsWorks AWS/OpsWo Monitoring Stacks using Amazon CloudWatch rks 2809 Amazon CloudWatch User Guide Service Namespace Documentation AWS Outposts AWS/Outpo CloudWatch metrics for AWS Outposts sts AWS Panorama AWS/Panor amaDevice Metrics Monitoring appliances and applications with Amazon CloudWatch Amazon Personalize Amazon Pinpoint AWS/Perso CloudWatch metrics for Amazon Personalize nalize
acw-ug-805
acw-ug.pdf
805
yDB Amazon MQ AWS/Amazo nMQ Monitoring Amazon MQ Brokers Using Amazon CloudWatch Amazon Neptune AWS/Neptune Monitoring Neptune with CloudWatch AWS Network Firewall AWS/Netwo rkFirewall AWS Network Manager AWS/Netwo rkManager AWS Network Firewall metrics in Amazon CloudWatch CloudWatch metrics for on-premises resources AWS HealthOmi cs AWS/Omics Monitoring AWS HealthOmics with Amazon CloudWatch AWS OpsWorks AWS/OpsWo Monitoring Stacks using Amazon CloudWatch rks 2809 Amazon CloudWatch User Guide Service Namespace Documentation AWS Outposts AWS/Outpo CloudWatch metrics for AWS Outposts sts AWS Panorama AWS/Panor amaDevice Metrics Monitoring appliances and applications with Amazon CloudWatch Amazon Personalize Amazon Pinpoint AWS/Perso CloudWatch metrics for Amazon Personalize nalize AWS/Pinpo View Amazon Pinpoint metrics in CloudWatch int Amazon Polly AWS/Polly Integrating CloudWatch with Amazon Polly AWS PrivateLink AWS/Priva CloudWatch metrics for AWS PrivateLink teLinkEnd points AWS PrivateLink AWS/Priva CloudWatch metrics for AWS PrivateLink teLinkSer vices AWS Private 5G AWS/Priva Amazon CloudWatch metrics te5G Amazon Q Apps AWS/QApps Monitoring Amazon Q Business and Amazon Q Apps with Amazon CloudWatch Amazon Q Business Amazon Q Developer AWS/QBusi ness AWS/Q Monitoring Amazon Q Business and Amazon Q Apps with Amazon CloudWatch Monitoring Amazon Q Developer with Amazon CloudWatch Amazon QLDB AWS/QLDB Monitoring data in Amazon QuickSight 2810 Amazon CloudWatch User Guide Service Namespace Documentation Amazon QuickSight Amazon Redshift Amazon Relationa l Database Service Amazon Rekognition AWS/Quick Monitoring with Amazon CloudWatch Sight AWS/Redsh Amazon Redshift Performance Data ift AWS/RDS Monitoring Amazon RDS metrics with Amazon CloudWatch AWS/Rekog Monitoring Rekognition with Amazon CloudWatch nition AWS re:Post Private AWS/rePos tPrivate Monitoring AWS re:Post Private with Amazon CloudWatc h AWS RoboMaker AWS/Robom Monitoring AWS RoboMaker with Amazon CloudWatch Amazon Route 53 Route 53 Application Recovery Controller Amazon SageMaker AI aker AWS/Route53 Monitoring Amazon Route 53 AWS/Route 53Recover yReadiness Using Amazon CloudWatch with Application Recovery Controller AWS/SageM Monitoring SageMaker AI with CloudWatch aker Amazon SageMaker AI Model Building Pipelines AWS/SageM aker/Mode lBuilding Pipeline SageMaker AI Pipelines Metrics 2811 Amazon CloudWatch User Guide Service Namespace Documentation AWS Secrets Manager AWS/Secre tsManager Monitoring Secrets Manager with Amazon CloudWatch Amazon Security Lake AWS/Secur CloudWatch metrics for Amazon Security Lake ityLake Service Catalog AWS/Servi Service Catalog CloudWatch Metrics ceCatalog AWS Shield Advanced AWS/DDoSP rotection Monitoring with CloudWatch Amazon Simple Email Service AWS/SES Retrieving Amazon SES Event Data from CloudWatch AWS SimSpace Weaver AWS/simsp aceweaver Monitoring AWS SimSpace Weaver with Amazon CloudWatch Amazon Simple Notification Service Amazon Simple Queue Service AWS/SNS Monitoring Amazon SNS with CloudWatch AWS/SQS Monitoring Amazon SQS Queues Using CloudWatch Amazon S3 AWS/S3 Monitoring Metrics with Amazon CloudWatch S3 Storage Lens AWS/S3/St Monitor S3 Storage Lens metrics in CloudWatch orage-Lens Amazon Simple Workflow Service AWS Step Functions AWS/SWF Amazon SWF Metrics for CloudWatch AWS/States Monitoring Step Functions Using CloudWatch 2812 Amazon CloudWatch User Guide Service Namespace Documentation AWS Storage Gateway AWS/Stora geGateway AWS Systems Manager Run Command AWS/SSM-R unCommand Using Amazon CloudWatch metrics Monitoring Run Command Metrics Using CloudWatch Amazon Textract AWS/Textr CloudWatch Metrics for Amazon Textract act Amazon Timestream AWS Transfer for SFTP Amazon Transcribe Amazon Translate AWS/Times Timestream Metrics and Dimensions tream AWS/Trans AWS SFTP CloudWatch Metrics fer AWS/Trans cribe Monitoring Amazon Transcribe with Amazon CloudWatc h AWS/Trans late CloudWatch Metrics and Dimensions for Amazon Translate AWS Trusted Advisor AWS/Trust edAdvisor Creating Trusted Advisor Alarms Using CloudWatch Amazon VPC AWS/NATGa Monitoring Your NAT Gateway with CloudWatch Amazon VPC teway AWS/Trans itGateway CloudWatch Metrics for Your Transit Gateways Amazon VPC AWS/VPN Monitoring with CloudWatch Amazon VPC IP Address Manager AWS/IPAM Create alarms with Amazon CloudWatch 2813 Amazon CloudWatch User Guide Service Namespace Documentation AWS WAF Amazon WorkMail Amazon WorkSpaces Amazon WorkSpaces Web Monitoring with CloudWatch AWS/WAFV2 for AWS WAF resources WAF for AWS WAF classic resources AWS/WorkM Monitoring Amazon WorkMail with Amazon CloudWatch ail AWS/WorkS Monitor Your WorkSpaces Using CloudWatch Metrics paces AWS/WorkS pacesWeb Monitoring Amazon WorkSpaces Web with Amazon CloudWatch 2814 Amazon CloudWatch User Guide AWS usage metrics CloudWatch collects metrics that track the usage of some AWS resources and APIs. These metrics are published in the AWS/Usage namespace. Usage metrics in CloudWatch allow you to proactively manage usage by visualizing metrics in the CloudWatch console, creating custom dashboards, detecting changes in activity with CloudWatch anomaly detection, and configuring alarms that alert you when usage approaches a threshold. Some AWS services integrate these usage metrics with Service Quotas. For these services, you can use CloudWatch to manage your account's use of your service quotas. For more information, see Visualizing your service quotas and setting alarms. Topics • Visualizing your service quotas and setting alarms • AWS API usage metrics • CloudWatch usage metrics Visualizing your service quotas and setting alarms For some AWS services, you can use the usage metrics to visualize your current service usage on CloudWatch graphs and dashboards. You can use a CloudWatch metric math function to display the service quotas for those resources on your graphs. You can also configure alarms that alert
acw-ug-806
acw-ug.pdf
806
Quotas. For these services, you can use CloudWatch to manage your account's use of your service quotas. For more information, see Visualizing your service quotas and setting alarms. Topics • Visualizing your service quotas and setting alarms • AWS API usage metrics • CloudWatch usage metrics Visualizing your service quotas and setting alarms For some AWS services, you can use the usage metrics to visualize your current service usage on CloudWatch graphs and dashboards. You can use a CloudWatch metric math function to display the service quotas for those resources on your graphs. You can also configure alarms that alert you when your usage approaches a service quota. For more information about service quotas, see What Is Service Quotas in the Service Quotas User Guide. If you are signed in to an account that is set up as a monitoring account in CloudWatch cross- account observability, you can use that monitoring account to visualize service quotas and set alarms for metrics in the source accounts that are linked to that monitoring account. For more information, see CloudWatch cross-account observability. Currently, the following services integrate their usage metrics with Service Quotas: • AWS CloudHSM • Amazon Chime SDK • Amazon CloudWatch Visualizing your service quotas and setting alarms 2815 User Guide Amazon CloudWatch • Amazon CloudWatch Logs • Amazon DynamoDB • Amazon EC2 • Amazon Elastic Container Registry • Elastic Load Balancing • AWS Fargate • AWS Fault Injection Service • AWS Interactive Video Service • AWS Key Management Service • Amazon Data Firehose • Amazon Location Service • Amazon Managed Blockchain (AMB) Query • AWS RoboMaker • Amazon SageMaker AI To visualize a service quota and optionally set an alarm 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Metrics. 3. On the All metrics tab, choose Usage, and then choose By AWS Resource. The list of service quota usage metrics appears. 4. Select the check box next to one of the metrics. The graph displays your current usage of that AWS resource. 5. To add your service quota to the graph, do the following: a. Choose the Graphed metrics tab. b. Choose Math expression, Start with an empty expression. In the new row, under Details, enter SERVICE_QUOTA(m1). A new line is added to the graph, displaying the service quota for the resource represented in the metric. Visualizing your service quotas and setting alarms 2816 Amazon CloudWatch User Guide 6. To see your current usage as a percentage of the quota, add a new expression or change the current SERVICE_QUOTA expression. The new expression to use is m1/ SERVICE_QUOTA(m1)*100. 7. (Optional) To set an alarm that notifies you if you approach the service quota, do the following: a. On the row with m1/SERVICE_QUOTA(m1)*100, under Actions, choose the alarm icon. It looks like a bell. The alarm creation page appears. b. Under Conditions, ensure that Threshold type is Static and Whenever Expression1 is is set to Greater. Under than, enter 80. This creates an alarm that goes into ALARM state when your usage exceeds 80 percent of the quota. c. Choose Next. d. On the next page, select an Amazon SNS topic or create a new one, and then choose Next. The topic you select is notified when the alarm goes to ALARM state. e. On the next page, enter a name and description for the alarm, and then choose Next. f. Choose Create alarm. AWS API usage metrics Most APIs that support AWS CloudTrail logging also report usage metrics to CloudWatch. API usage metrics in CloudWatch allow you to proactively manage API usage by visualizing metrics in the CloudWatch console, creating custom dashboards, detecting changes in activity with CloudWatch Anomaly Detection, and configuring alarms that alert when usage approaches a threshold. You can use the he following table to learn about services that report API usage metrics to CloudWatch. The table lists the values to use for the Service dimension, so you can see the usage metrics from that service. You can use the procedure in this section to view the list of a service's APIs that report usage metrics to CloudWatch. Service Value for the Service dimension AWS Identity and Access Management Access Analyzer Access Analyzer AWS API usage metrics 2817 Amazon CloudWatch Service Value for the Service dimension User Guide AWS Account Management Account Management Alexa for Business Amazon API Gateway AWS App Mesh AWS AppConfig Amazon AppFlow A4B API Gateway App Mesh AWS AppConfig AppFlow Application Auto Scaling Application Auto Scaling Application Discovery Service Application Discovery Service Amazon AppStream AppStream AppStream 2.0 Image Builder Image Builder Amazon Athena Athena AWS Audit Manager Audit Manager AWS Backup AWS Batch Amazon Braket AWS Budgets Backup Batch Braket Budgets AWS Certificate Manager Certificate Manager Amazon Chime SDK ChimeSDK Amazon Cloud Directory Cloud Directory AWS Cloud Map
acw-ug-807
acw-ug.pdf
807
Analyzer AWS API usage metrics 2817 Amazon CloudWatch Service Value for the Service dimension User Guide AWS Account Management Account Management Alexa for Business Amazon API Gateway AWS App Mesh AWS AppConfig Amazon AppFlow A4B API Gateway App Mesh AWS AppConfig AppFlow Application Auto Scaling Application Auto Scaling Application Discovery Service Application Discovery Service Amazon AppStream AppStream AppStream 2.0 Image Builder Image Builder Amazon Athena Athena AWS Audit Manager Audit Manager AWS Backup AWS Batch Amazon Braket AWS Budgets Backup Batch Braket Budgets AWS Certificate Manager Certificate Manager Amazon Chime SDK ChimeSDK Amazon Cloud Directory Cloud Directory AWS Cloud Map Cloud Map AWS API usage metrics 2818 Amazon CloudWatch Service Value for the Service dimension User Guide AWS CloudFormation CloudFormation AWS CloudHSM Amazon CloudSearch AWS CloudShell AWS CloudTrail Amazon CloudWatch CloudHSM CloudSearch CloudShell CloudTrail CloudWatch Amazon CloudWatch Application Signals CloudWatch Application Signals Amazon CloudWatch Logs Logs Amazon CloudWatch Application Insights CloudWatch Application Insights AWS CodeBuild AWS CodeCommit CodeBuild CodeCommit Amazon CodeGuru Profiler CodeGuru Profiler AWS CodePipeline AWS CodeStar CodePipeline CodeStar AWS CodeStar Notifications CodeStar Notifications AWS CodeStar Connections CodeStar Connections Amazon Cognito Identity pools Cognito Identity Pools Amazon Cognito Sync Amazon Comprehend Cognito Sync Comprehend Amazon Comprehend Medical Comprehend Medical AWS API usage metrics 2819 Amazon CloudWatch Service Value for the Service dimension User Guide AWS Compute Optimizer ComputeOptimzier Amazon Connect Connect Amazon Connect Customer Profiles Customer Profiles AWS Cost and Usage Reports Cost and Usage Report AWS Cost Explorer AWS Data Exchange Cost Explorer Data Exchange AWS Data Lifecycle Manager Data Lifecycle Manager AWS Database Migration Service Database Migration Service AWS DataSync AWS DeepLens Amazon Detective Device Advisor AWS Direct Connect DataSync AWS DeepLens Detective Device Advisor Direct Connect AWS Directory Service Directory Service DynamoDB Accelerator DynamoDBAccelerator Amazon EC2 EC2 Auto Scaling EC2 EC2 Auto Scaling Amazon Elastic Container Registry ECR Public Amazon Elastic Container Service Amazon Elastic File System ECS EFS AWS API usage metrics 2820 Amazon CloudWatch Service Value for the Service dimension User Guide Amazon Elastic Kubernetes Service EKS AWS Elastic Beanstalk Elastic Beanstalk Amazon Elastic Inference Elastic Inference Elastic Load Balancing Elastic Load Balancing Amazon EMR EMR Containers AWS Firewall Manager Firewall Manager Amazon FSx Amazon GameLift Servers AWS Glue DataBrew Amazon Managed Grafana FSx GameLift DataBrew Grafana AWS IoT Greengrass Greengrass AWS Ground Station Ground Station AWS Health APIs And Notifications AWS Health APIs And Notifications Amazon Interactive Video Service AWS IoT Core AWS IoT Events IVS IoT IoT Events AWS IoT RoboRunner IoT RoboRunner AWS IoT SiteWise AWS IoT Wireless Amazon Kendra IoT Sitewise IoT Wireless Kendra AWS API usage metrics 2821 Amazon CloudWatch Service Value for the Service dimension User Guide Amazon Keyspaces (for Apache Cassandra) Keyspaces Amazon Managed Service for Apache Flink Kinesis Analytics Amazon Data Firehose Firehose Kinesis Video Streams Kinesis Video Streams AWS Key Management Service AWS Lambda KMS Lambda AWS Launch Wizard Launch Wizard Amazon Lex Amazon Lightsail Amazon Location Service Amazon Lex Lightsail Location Amazon Lookout for Vision Lookout for Vision Amazon Machine Learning Amazon Machine Learning Amazon Macie Macie Amazon Managed Blockchain (AMB) Query Amazon Managed Blockchain Query AWS Managed Services AWS Managed Services AWS Marketplace Commerce Analytics Marketplace Analytics Service AWS Elemental MediaConnect MediaConnect AWS Elemental MediaConvert MediaConvert AWS Elemental MediaLive AWS Elemental MediaStore MediaLive Mediastore AWS API usage metrics 2822 Amazon CloudWatch Service Value for the Service dimension User Guide AWS Elemental MediaTailor AWS Mobile Hub MediaTailor Mobile Hub AWS Network Firewall Network Firewall AWS OpsWorks AWS OpsWorks for Configuration Managemen t OpsWorks OPsWorks CM AWS Outposts Outposts AWS Organizations Organizations Amazon RDS Performance Insights Performance Insights Amazon Pinpoint Pinpoint AWS Private Certificate Authority Private Certificate Authority Amazon Managed Service for Prometheus Prometheus AWS Proton Amazon Quantum Ledger Database (Amazon QLDB) Amazon RDS Amazon Redshift Proton QLDB RDS Redshift Data API Amazon Rekognition Rekognition AWS Resource Access Manager Resource Access Manager AWS Resource Groups Resource Groups AWS Resource Groups Tagging API Resource Groups Tagging API AWS API usage metrics 2823 Amazon CloudWatch Service Value for the Service dimension User Guide AWS RoboMaker RoboMaker Amazon Route 53 Domains Route 53 Domains Amazon Route 53 Resolver Route 53 Resolver Amazon S3 S3 Amazon S3 Glacier Amazon S3 Glacier Amazon SageMaker Runtime Sagemaker Savings Plans Savings Plans AWS Secrets Manager Secrets Manager AWS Security Hub Security Hub AWS Server Migration Service AWS Server Migration Service AWS Service Catalog AppRegistry Service Catalog AppRegistry Service Quotas AWS Shield AWS Signer Amazon Simple Notification Service Amazon Simple Email Service Amazon Simple Queue Service Identity Store Storage Gateway AWS Support Service Quotas Shield Signer SNS SES SQS Identity Store Storage Gateway Support AWS API usage metrics 2824 Amazon CloudWatch Service Value for the Service dimension User Guide Amazon Simple Workflow Service SWF Amazon Textract AWS IoT Things Graph Amazon Timestream Amazon Transcribe Amazon Translate Textract ThingsGraph Timestream Transcribe Translate Amazon Transcribe
acw-ug-808
acw-ug.pdf
808
AWS Secrets Manager Secrets Manager AWS Security Hub Security Hub AWS Server Migration Service AWS Server Migration Service AWS Service Catalog AppRegistry Service Catalog AppRegistry Service Quotas AWS Shield AWS Signer Amazon Simple Notification Service Amazon Simple Email Service Amazon Simple Queue Service Identity Store Storage Gateway AWS Support Service Quotas Shield Signer SNS SES SQS Identity Store Storage Gateway Support AWS API usage metrics 2824 Amazon CloudWatch Service Value for the Service dimension User Guide Amazon Simple Workflow Service SWF Amazon Textract AWS IoT Things Graph Amazon Timestream Amazon Transcribe Amazon Translate Textract ThingsGraph Timestream Transcribe Translate Amazon Transcribe streaming transcription Transcribe Streaming AWS Transfer Family AWS WAF Amazon WorkDocs Amazon WorkLink Amazon WorkMail Amazon WorkSpaces AWS X-Ray Transfer WAF Amazon WorkDocs WorkLink Amazon WorkMail Workspaces X-Ray Some services report usage metrics for additional APIs as well. To see whether an API reports usage metrics to CloudWatch, use the CloudWatch console to see the metrics reported by that service in the AWS/Usage namespace. To see the list of a service's APIs that report usage metrics to CloudWatch 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Metrics. 3. On the All metrics tab, choose Usage, and then choose By AWS Resource. AWS API usage metrics 2825 Amazon CloudWatch User Guide 4. In the search box near the list of metrics, enter the name of the service. The metrics are filtered by the service you entered. CloudWatch usage metrics CloudWatch collects metrics that track the usage of some AWS resources. These metrics correspond to AWS service quotas. Tracking these metrics can help you proactively manage your quotas. For more information, see Visualizing your service quotas and setting alarms. Service quota usage metrics are in the AWS/Usage namespace and are collected every minute. The metrics that can be published in this namespace include CallCount, ResourceCount, and ThrottleCount. These metrics are published with the dimensions Resource, Service, and Type. The Resource dimension specifies the name of the API operation being tracked. For example, the CallCount metric with the dimensions "Service": "CloudWatch", "Type": "API" and "Resource": "PutMetricData" indicates the number of times the CloudWatch PutMetricData API operation has been called in your account. The CallCount metric does not have a specified unit. The most useful statistic for the metric is SUM, which represents the total operation count for the 1-minute period. Metrics Metric Description CallCount The number of specified operations performed in your account. Dimensions Dimension Description Service The name of the AWS service containing the resource. For CloudWatch usage metrics, the value for this dimension is CloudWatch . Class The class of resource being tracked. CloudWatch API usage metrics use this dimension with a value of None. CloudWatch usage metrics 2826 Amazon CloudWatch User Guide Dimension Description Type The type of resource being tracked. Currently, when the Service dimension is CloudWatch , the only valid value for Type is API. Resource The name of the API operation. Valid values include the following: DeleteAlarms , DeleteDashboards , DescribeAlarmHisto ry , DescribeAlarms , GetDashboard , GetMetricData , GetMetricStatistics , ListMetrics , PutDashboard , and PutMetricData CloudWatch usage metrics 2827 Amazon CloudWatch User Guide Amazon CloudWatch tutorials The following scenarios illustrate how you can use Amazon CloudWatch. In the first scenario, you use the CloudWatch console to create a billing alarm that tracks your AWS usage and lets you know when you have exceeded a certain spending threshold. In the second scenario, you use the AWS Command Line Interface (AWS CLI) to publish a single metric for a hypothetical application named GetStarted. Scenarios • Monitor your estimated charges • Publish metrics Scenario: Monitor your estimated charges using CloudWatch In this scenario, you create an Amazon CloudWatch alarm to monitor your estimated charges. When you enable the monitoring of estimated charges for your AWS account, the estimated charges are calculated and sent several times daily to CloudWatch as metric data. Billing metric data is stored in the US East (N. Virginia) Region and reflects worldwide charges. This data includes the estimated charges for every service in AWS that you use, as well as the estimated overall total of your AWS charges. You can choose to receive alerts by email when charges have exceeded a certain threshold. These alerts are triggered by CloudWatch and messages are sent using Amazon Simple Notification Service (Amazon SNS). Note For information about analyzing CloudWatch charges that you have already been billed for, see Analyzing, optimizing, and reducing CloudWatch costs. Tasks • Step 1: Enable billing alerts • Step 2: Create a billing alarm Scenario: Monitor estimated charges 2828 Amazon CloudWatch • Step 3: Check the alarm status • Step 4: Edit a billing alarm • Step 5: Delete a billing alarm Step 1: Enable billing alerts User Guide Before you can create an alarm for your estimated
acw-ug-809
acw-ug.pdf
809
exceeded a certain threshold. These alerts are triggered by CloudWatch and messages are sent using Amazon Simple Notification Service (Amazon SNS). Note For information about analyzing CloudWatch charges that you have already been billed for, see Analyzing, optimizing, and reducing CloudWatch costs. Tasks • Step 1: Enable billing alerts • Step 2: Create a billing alarm Scenario: Monitor estimated charges 2828 Amazon CloudWatch • Step 3: Check the alarm status • Step 4: Edit a billing alarm • Step 5: Delete a billing alarm Step 1: Enable billing alerts User Guide Before you can create an alarm for your estimated charges, you must enable billing alerts, so that you can monitor your estimated AWS charges and create an alarm using billing metric data. After you enable billing alerts, you cannot disable data collection, but you can delete any billing alarms that you created. After you enable billing alerts for the first time, it takes about 15 minutes before you can view billing data and set billing alarms. Requirements • You must be signed in using root user credentials or as a user who has been given permission to view billing information. • For consolidated billing accounts, billing data for each linked account can be found by logging in as the paying account. You can view billing data for total estimated charges and estimated charges by service for each linked account, in addition to the consolidated account. • In a consolidated billing account, member linked account metrics are captured only if the payer account enables the Receive Billing Alerts preference. If you change which account is your management/payer account, you must enable the billing alerts in the new management/payer account. • The account must not be part of the Amazon Partner Network (APN) because billing metrics are not published to CloudWatch for APN accounts. For more information, see AWS Partner Network. To enable the monitoring of estimated charges 1. Open the AWS Billing and Cost Management console at https://console.aws.amazon.com/ costmanagement/. 2. In the navigation pane, choose Billing Preferences. 3. By Alert preferences choose Edit. 4. Choose Receive CloudWatch Billing Alerts. 5. Choose Save preferences. Step 1: Enable billing alerts 2829 Amazon CloudWatch User Guide Step 2: Create a billing alarm Important Before you create a billing alarm, you must set your Region to US East (N. Virginia). Billing metric data is stored in this Region and represents worldwide charges. You also must enable billing alerts for your account or in the management/payer account (if you are using consolidated billing). For more information, see Step 1: Enable billing alerts. In this procedure, you create an alarm that sends a notification when your estimated charges for AWS exceed a defined threshold. To create a billing alarm using the CloudWatch console 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Alarms, and then choose All alarms. 3. Choose Create alarm. 4. Choose Select metric. In the Browse tab, choose Billing, and then choose Total Estimated Charge. Note If you don't see the Billing/Total Estimated Charge metric, enable billing alerts, and change your Region to US East (N. Virginia). For more information, see Enabling billing alerts. Select the checkbox for the EstimatedCharges metric, and then choose Select metric. For Statistic, choose Maximum. For Period, choose 6 hours. For Threshold type, choose Static. For Whenever EstimatedCharges is . . ., choose Greater. 5. 6. 7. 8. 9. 10. For than . . ., define the value that you want to cause your alarm to trigger. For example, 200 USD. The EstimatedCharges metric values are only in US dollars (USD), and the currency conversion is provided by Amazon Services LLC. For more information, see What is AWS Billing?. Step 2: Create a billing alarm 2830 Amazon CloudWatch User Guide 11. Choose Additional Configuration and do the following: • For Datapoints to alarm, specify 1 out of 1. • For Missing data treatment, choose Treat missing data as missing. 12. Choose Next. 13. Under Notification, ensure that In alarm is selected. Then specify an Amazon SNS topic to be notified when your alarm is in the ALARM state. The Amazon SNS topic can include your email address so that you recieve email when the billing amount crosses the threshold that you specified. You can select an existing Amazon SNS topic, create a new Amazon SNS topic, or use a topic ARN to notify other account. If you want your alarm to send multiple notifications for the same alarm state or for different alarm states, choose Add notification. 14. Choose Next. 15. Under Name and description, enter a name for your alarm. • (Optional) Enter a description of your alarm. 16. Choose Next. 17. Under Preview and create, make sure that your configuration is correct, and then choose Create alarm. Step 3: Check the alarm
acw-ug-810
acw-ug.pdf
810
billing amount crosses the threshold that you specified. You can select an existing Amazon SNS topic, create a new Amazon SNS topic, or use a topic ARN to notify other account. If you want your alarm to send multiple notifications for the same alarm state or for different alarm states, choose Add notification. 14. Choose Next. 15. Under Name and description, enter a name for your alarm. • (Optional) Enter a description of your alarm. 16. Choose Next. 17. Under Preview and create, make sure that your configuration is correct, and then choose Create alarm. Step 3: Check the alarm status Now, check the status of the billing alarm that you just created. To check the alarm status 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. If necessary, change the Region to US East (N. Virginia). Billing metric data is stored in this 3. 4. Region and reflects worldwide charges. In the navigation pane, choose Alarms, All alarms. Find the row in the table for your new alarm. Until the subscription is confirmed, it is shown as "Pending confirmation". After the subscription is confirmed, refresh the console to show the updated status. Step 3: Check the alarm status 2831 Amazon CloudWatch User Guide Step 4: Edit a billing alarm For example, you may want to increase the amount of money you spend with AWS each month from $200 to $400. You can edit your existing billing alarm and increase the monetary amount that must be exceeded before the alarm is triggered. To edit a billing alarm 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. If necessary, change the Region to US East (N. Virginia). Billing metric data is stored in this 3. 4. 5. Region and reflects worldwide charges. In the navigation pane, choose Alarms, All alarms. Select the checkbox next to the alarm and choose Actions, Edit. For than..., specify the new amount that must be exceeded to trigger the alarm and send an email notification. 6. Choose Save Changes. Step 5: Delete a billing alarm If you no longer need your billing alarm, you can delete it. To delete a billing alarm 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. If necessary, change the Region to US East (N. Virginia). Billing metric data is stored in this Region and reflects worldwide charges. In the navigation pane, choose Alarms, All alarms. Select the checkbox next to the alarm and choose Actions, Delete. 3. 4. 5. When prompted for confirmation, choose Yes, Delete. Scenario: Publish metrics to CloudWatch In this scenario, you use the AWS Command Line Interface (AWS CLI) to publish a single metric for a hypothetical application named GetStarted. If you haven't already installed and configured the AWS CLI, see Getting Set Up with the AWS Command Line Interface in the AWS Command Line Interface User Guide. Step 4: Edit a billing alarm 2832 Amazon CloudWatch Tasks • Step 1: Define the data configuration • Step 2: Add metrics to CloudWatch • Step 3: Get statistics from CloudWatch • Step 4: View graphs with the console User Guide Step 1: Define the data configuration In this scenario, you publish data points that track the request latency for the application. Choose names for your metric and namespace that make sense to you. For this example, name the metric RequestLatency and place all of the data points into the GetStarted namespace. You publish several data points that collectively represent three hours of latency data. The raw data comprises 15 request latency readings distributed over three hours. Each reading is in milliseconds: • Hour one: 87, 51, 125, 235 • Hour two: 121, 113, 189, 65, 89 • Hour three: 100, 47, 133, 98, 100, 328 You can publish data to CloudWatch as single data points or as an aggregated set of data points called a statistic set. You can aggregate metrics to a granularity as low as one minute. You can publish the aggregated data points to CloudWatch as a set of statistics with four predefined keys: Sum, Minimum, Maximum, and SampleCount. You publish the data points from hour one as single data points. For the data from hours two and three, you aggregate the data points and publish a statistic set for each hour. The key values are shown in the following table. Hour Raw data Sum Minimum Maximum SampleCou nt 1 1 87 51 Step 1: Define the data configuration 2833 Amazon CloudWatch Hour Raw data Sum Minimum Maximum User Guide SampleCou nt 1 1 2 3 125 235 121, 113, 189, 65, 89 100, 47, 133, 98, 100, 328 577 806 65 47 189 328 5 6 Step 2: Add metrics to CloudWatch After you have defined your data configuration, you are ready to add data. To publish data points to CloudWatch 1. At a command prompt,
acw-ug-811
acw-ug.pdf
811
statistic set for each hour. The key values are shown in the following table. Hour Raw data Sum Minimum Maximum SampleCou nt 1 1 87 51 Step 1: Define the data configuration 2833 Amazon CloudWatch Hour Raw data Sum Minimum Maximum User Guide SampleCou nt 1 1 2 3 125 235 121, 113, 189, 65, 89 100, 47, 133, 98, 100, 328 577 806 65 47 189 328 5 6 Step 2: Add metrics to CloudWatch After you have defined your data configuration, you are ready to add data. To publish data points to CloudWatch 1. At a command prompt, run the following put-metric-data commands to add data for the first hour. Replace the example timestamp with a timestamp that is two hours in the past, in Universal Coordinated Time (UTC). aws cloudwatch put-metric-data --metric-name RequestLatency --namespace GetStarted \ --timestamp 2016-10-14T20:30:00Z --value 87 --unit Milliseconds aws cloudwatch put-metric-data --metric-name RequestLatency --namespace GetStarted \ --timestamp 2016-10-14T20:30:00Z --value 51 --unit Milliseconds aws cloudwatch put-metric-data --metric-name RequestLatency --namespace GetStarted \ --timestamp 2016-10-14T20:30:00Z --value 125 --unit Milliseconds aws cloudwatch put-metric-data --metric-name RequestLatency --namespace GetStarted \ --timestamp 2016-10-14T20:30:00Z --value 235 --unit Milliseconds 2. Add data for the second hour, using a timestamp that is one hour later than the first hour. aws cloudwatch put-metric-data --metric-name RequestLatency --namespace GetStarted \ Step 2: Add metrics to CloudWatch 2834 Amazon CloudWatch User Guide --timestamp 2016-10-14T21:30:00Z --statistic-values Sum=577,Minimum=65,Maximum=189,SampleCount=5 --unit Milliseconds 3. Add data for the third hour, omitting the timestamp to default to the current time. aws cloudwatch put-metric-data --metric-name RequestLatency --namespace GetStarted \ --statistic-values Sum=806,Minimum=47,Maximum=328,SampleCount=6 --unit Milliseconds Step 3: Get statistics from CloudWatch Now that you have published metrics to CloudWatch, you can retrieve statistics based on those metrics using the get-metric-statistics command as follows. Be sure to specify --start-time and --end-time far enough in the past to cover the earliest timestamp that you published. aws cloudwatch get-metric-statistics --namespace GetStarted --metric-name RequestLatency --statistics Average \ --start-time 2016-10-14T00:00:00Z --end-time 2016-10-15T00:00:00Z --period 60 The following is example output: { "Datapoints": [], "Label": "Request:Latency" } Step 4: View graphs with the console After you have published metrics to CloudWatch, you can use the CloudWatch console to view statistical graphs. To view graphs of your statistics on the console 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the Navigation pane, choose Metrics. 3. On the All metrics tab, in the search box, type RequestLatency and press Enter. 4. Select the check box for the RequestLatency metric. A graph of the metric data is displayed in the upper pane. Step 3: Get statistics from CloudWatch 2835 Amazon CloudWatch User Guide For more information, see Graphing metrics. Step 4: View graphs with the console 2836 Amazon CloudWatch User Guide Using CloudWatch with an AWS SDK AWS software development kits (SDKs) are available for many popular programming languages. Each SDK provides an API, code examples, and documentation that make it easier for developers to build applications in their preferred language. SDK documentation Code examples AWS SDK for C++ AWS SDK for C++ code examples AWS CLI AWS SDK for Go AWS SDK for Java AWS CLI code examples AWS SDK for Go code examples AWS SDK for Java code examples AWS SDK for JavaScript AWS SDK for JavaScript code examples AWS SDK for Kotlin AWS SDK for Kotlin code examples AWS SDK for .NET AWS SDK for PHP AWS SDK for .NET code examples AWS SDK for PHP code examples AWS Tools for PowerShell Tools for PowerShell code examples AWS SDK for Python (Boto3) AWS SDK for Python (Boto3) code examples AWS SDK for Ruby AWS SDK for Rust AWS SDK for Ruby code examples AWS SDK for Rust code examples AWS SDK for SAP ABAP AWS SDK for SAP ABAP code examples AWS SDK for Swift AWS SDK for Swift code examples For examples specific to CloudWatch, see Code examples for CloudWatch using AWS SDKs. 2837 Amazon CloudWatch User Guide Example availability Can't find what you need? Request a code example by using the Provide feedback link at the bottom of this page. 2838 Amazon CloudWatch User Guide Code examples for CloudWatch using AWS SDKs The following code examples show how to use CloudWatch with an AWS software development kit (SDK). Basics are code examples that show you how to perform the essential operations within a service. 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. Scenarios are code examples that show you how to accomplish specific tasks by calling multiple functions within a service or combined with other AWS services. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and
acw-ug-812
acw-ug.pdf
812
code examples that show you how to perform the essential operations within a service. 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. Scenarios are code examples that show you how to accomplish specific tasks by calling multiple functions within a service or combined with other AWS services. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Get started Hello CloudWatch The following code examples show how to get started using CloudWatch. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using Amazon.CloudWatch; using Amazon.CloudWatch.Model; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace CloudWatchActions; 2839 Amazon CloudWatch User Guide public static class HelloCloudWatch { static async Task Main(string[] args) { // Use the AWS .NET Core Setup package to set up dependency injection for the Amazon CloudWatch service. // Use your AWS profile name, or leave it blank to use the default profile. using var host = Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService<IAmazonCloudWatch>() ).Build(); // Now the client is available for injection. var cloudWatchClient = host.Services.GetRequiredService<IAmazonCloudWatch>(); // You can use await and any of the async methods to get a response. var metricNamespace = "AWS/Billing"; var response = await cloudWatchClient.ListMetricsAsync(new ListMetricsRequest { Namespace = metricNamespace }); Console.WriteLine($"Hello Amazon CloudWatch! Following are some metrics available in the {metricNamespace} namespace:"); Console.WriteLine(); foreach (var metric in response.Metrics.Take(5)) { Console.WriteLine($"\tMetric: {metric.MetricName}"); Console.WriteLine($"\tNamespace: {metric.Namespace}"); Console.WriteLine($"\tDimensions: {string.Join(", ", metric.Dimensions.Select(m => $"{m.Name}:{m.Value}"))}"); Console.WriteLine(); } } } • For API details, see ListMetrics in AWS SDK for .NET API Reference. 2840 Amazon CloudWatch Java SDK for Java 2.x Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest; import software.amazon.awssdk.services.cloudwatch.paginators.ListMetricsIterable; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class HelloService { public static void main(String[] args) { final String usage = """ Usage: <namespace>\s Where: namespace - The namespace to filter against (for example, AWS/ EC2).\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } 2841 Amazon CloudWatch User Guide String namespace = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() .region(region) .build(); listMets(cw, namespace); cw.close(); } public static void listMets(CloudWatchClient cw, String namespace) { try { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .build(); ListMetricsIterable listRes = cw.listMetricsPaginator(request); listRes.stream() .flatMap(r -> r.metrics().stream()) .forEach(metrics -> System.out.println(" Retrieved metric is: " + metrics.metricName())); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ListMetrics in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. 2842 Amazon CloudWatch /** User Guide Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <namespace> Where: namespace - The namespace to filter against (for example, AWS/EC2). """ if (args.size != 1) { println(usage) exitProcess(0) } val namespace = args[0] listAllMets(namespace) } suspend fun listAllMets(namespaceVal: String?) { val request = ListMetricsRequest { namespace = namespaceVal } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient .listMetricsPaginated(request) .transform { it.metrics?.forEach { obj -> emit(obj) } } .collect { obj -> println("Name is ${obj.metricName}") println("Namespace is ${obj.namespace}") } } } 2843 Amazon CloudWatch User Guide • For API details, see ListMetrics in AWS SDK for Kotlin API reference. Code examples • Basic examples for CloudWatch using AWS SDKs • Hello CloudWatch • Learn core operations for CloudWatch using an AWS SDK • Actions for CloudWatch using AWS SDKs • Use DeleteAlarms with an AWS SDK or CLI • Use DeleteAnomalyDetector with an AWS SDK or CLI • Use DeleteDashboards with an AWS SDK or CLI • Use DescribeAlarmHistory with an AWS SDK or CLI • Use DescribeAlarms with an AWS SDK or CLI • Use DescribeAlarmsForMetric with an AWS SDK or CLI • Use DescribeAnomalyDetectors with an AWS SDK or CLI • Use DisableAlarmActions with an AWS SDK or CLI • Use EnableAlarmActions with an AWS SDK or CLI • Use GetDashboard with an AWS SDK or CLI • Use GetMetricData with an AWS SDK or CLI • Use GetMetricStatistics with an AWS SDK or CLI • Use GetMetricWidgetImage with an
acw-ug-813
acw-ug.pdf
813
an AWS SDK or CLI • Use DeleteDashboards with an AWS SDK or CLI • Use DescribeAlarmHistory with an AWS SDK or CLI • Use DescribeAlarms with an AWS SDK or CLI • Use DescribeAlarmsForMetric with an AWS SDK or CLI • Use DescribeAnomalyDetectors with an AWS SDK or CLI • Use DisableAlarmActions with an AWS SDK or CLI • Use EnableAlarmActions with an AWS SDK or CLI • Use GetDashboard with an AWS SDK or CLI • Use GetMetricData with an AWS SDK or CLI • Use GetMetricStatistics with an AWS SDK or CLI • Use GetMetricWidgetImage with an AWS SDK or CLI • Use ListDashboards with an AWS SDK or CLI • Use ListMetrics with an AWS SDK or CLI • Use PutAnomalyDetector with an AWS SDK or CLI • Use PutDashboard with an AWS SDK or CLI • Use PutMetricAlarm with an AWS SDK or CLI • Use PutMetricData with an AWS SDK or CLI • Scenarios for CloudWatch using AWS SDKs • Get started with CloudWatch alarms using an AWS SDK • Manage CloudWatch metrics and alarms using an AWS SDK • Monitor performance of Amazon DynamoDB using an AWS SDK 2844 Amazon CloudWatch User Guide Basic examples for CloudWatch using AWS SDKs The following code examples show how to use the basics of Amazon CloudWatch with AWS SDKs. Examples • Hello CloudWatch • Learn core operations for CloudWatch using an AWS SDK • Actions for CloudWatch using AWS SDKs • Use DeleteAlarms with an AWS SDK or CLI • Use DeleteAnomalyDetector with an AWS SDK or CLI • Use DeleteDashboards with an AWS SDK or CLI • Use DescribeAlarmHistory with an AWS SDK or CLI • Use DescribeAlarms with an AWS SDK or CLI • Use DescribeAlarmsForMetric with an AWS SDK or CLI • Use DescribeAnomalyDetectors with an AWS SDK or CLI • Use DisableAlarmActions with an AWS SDK or CLI • Use EnableAlarmActions with an AWS SDK or CLI • Use GetDashboard with an AWS SDK or CLI • Use GetMetricData with an AWS SDK or CLI • Use GetMetricStatistics with an AWS SDK or CLI • Use GetMetricWidgetImage with an AWS SDK or CLI • Use ListDashboards with an AWS SDK or CLI • Use ListMetrics with an AWS SDK or CLI • Use PutAnomalyDetector with an AWS SDK or CLI • Use PutDashboard with an AWS SDK or CLI • Use PutMetricAlarm with an AWS SDK or CLI • Use PutMetricData with an AWS SDK or CLI Hello CloudWatch The following code examples show how to get started using CloudWatch. Basics 2845 Amazon CloudWatch .NET SDK for .NET Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using Amazon.CloudWatch; using Amazon.CloudWatch.Model; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace CloudWatchActions; public static class HelloCloudWatch { static async Task Main(string[] args) { // Use the AWS .NET Core Setup package to set up dependency injection for the Amazon CloudWatch service. // Use your AWS profile name, or leave it blank to use the default profile. using var host = Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService<IAmazonCloudWatch>() ).Build(); // Now the client is available for injection. var cloudWatchClient = host.Services.GetRequiredService<IAmazonCloudWatch>(); // You can use await and any of the async methods to get a response. var metricNamespace = "AWS/Billing"; var response = await cloudWatchClient.ListMetricsAsync(new ListMetricsRequest { Namespace = metricNamespace }); Hello CloudWatch 2846 Amazon CloudWatch User Guide Console.WriteLine($"Hello Amazon CloudWatch! Following are some metrics available in the {metricNamespace} namespace:"); Console.WriteLine(); foreach (var metric in response.Metrics.Take(5)) { Console.WriteLine($"\tMetric: {metric.MetricName}"); Console.WriteLine($"\tNamespace: {metric.Namespace}"); Console.WriteLine($"\tDimensions: {string.Join(", ", metric.Dimensions.Select(m => $"{m.Name}:{m.Value}"))}"); Console.WriteLine(); } } } • For API details, see ListMetrics in AWS SDK for .NET API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest; import software.amazon.awssdk.services.cloudwatch.paginators.ListMetricsIterable; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ Hello CloudWatch 2847 Amazon CloudWatch User Guide public class HelloService { public static void main(String[] args) { final String usage = """ Usage: <namespace>\s Where: namespace - The namespace to filter against (for example, AWS/ EC2).\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String namespace = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() .region(region) .build(); listMets(cw, namespace); cw.close(); } public static void listMets(CloudWatchClient cw, String namespace) { try { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .build(); ListMetricsIterable listRes = cw.listMetricsPaginator(request); listRes.stream() .flatMap(r -> r.metrics().stream()) .forEach(metrics -> System.out.println(" Retrieved metric is: " + metrics.metricName())); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } Hello CloudWatch 2848 Amazon
acw-ug-814
acw-ug.pdf
814
HelloService { public static void main(String[] args) { final String usage = """ Usage: <namespace>\s Where: namespace - The namespace to filter against (for example, AWS/ EC2).\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String namespace = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() .region(region) .build(); listMets(cw, namespace); cw.close(); } public static void listMets(CloudWatchClient cw, String namespace) { try { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .build(); ListMetricsIterable listRes = cw.listMetricsPaginator(request); listRes.stream() .flatMap(r -> r.metrics().stream()) .forEach(metrics -> System.out.println(" Retrieved metric is: " + metrics.metricName())); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } Hello CloudWatch 2848 Amazon CloudWatch } User Guide • For API details, see ListMetrics in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <namespace> Where: namespace - The namespace to filter against (for example, AWS/EC2). """ if (args.size != 1) { println(usage) exitProcess(0) } val namespace = args[0] listAllMets(namespace) } suspend fun listAllMets(namespaceVal: String?) { val request = Hello CloudWatch 2849 Amazon CloudWatch User Guide ListMetricsRequest { namespace = namespaceVal } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient .listMetricsPaginated(request) .transform { it.metrics?.forEach { obj -> emit(obj) } } .collect { obj -> println("Name is ${obj.metricName}") println("Namespace is ${obj.namespace}") } } } • For API details, see ListMetrics in AWS SDK for Kotlin API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Learn core operations for CloudWatch using an AWS SDK The following code examples show how to: • List CloudWatch namespaces and metrics. • Get statistics for a metric and for estimated billing. • Create and update a dashboard. • Create and add data to a metric. • Create and trigger an alarm, then view alarm history. • Add an anomaly detector. • Get a metric image, then clean up resources. Learn the basics 2850 Amazon CloudWatch .NET SDK for .NET Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Run an interactive scenario at a command prompt. public class CloudWatchScenario { /* Before running this .NET code example, set up your development environment, including your credentials. To enable billing metrics and statistics for this example, make sure billing alerts are enabled for your account: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ monitor_estimated_charges_with_cloudwatch.html#turning_on_billing_metrics This .NET example performs the following tasks: 1. List and select a CloudWatch namespace. 2. List and select a CloudWatch metric. 3. Get statistics for a CloudWatch metric. 4. Get estimated billing statistics for the last week. 5. Create a new CloudWatch dashboard with two metrics. 6. List current CloudWatch dashboards. 7. Create a CloudWatch custom metric and add metric data. 8. Add the custom metric to the dashboard. 9. Create a CloudWatch alarm for the custom metric. 10. Describe current CloudWatch alarms. 11. Get recent data for the custom metric. 12. Add data to the custom metric to trigger the alarm. 13. Wait for an alarm state. 14. Get history for the CloudWatch alarm. 15. Add an anomaly detector. 16. Describe current anomaly detectors. 17. Get and display a metric image. 18. Clean up resources. */ Learn the basics 2851 Amazon CloudWatch User Guide private static ILogger logger = null!; private static CloudWatchWrapper _cloudWatchWrapper = null!; private static IConfiguration _configuration = null!; private static readonly List<string> _statTypes = new List<string> { "SampleCount", "Average", "Sum", "Minimum", "Maximum" }; private static SingleMetricAnomalyDetector? anomalyDetector = null!; static async Task Main(string[] args) { // Set up dependency injection for the Amazon service. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonCloudWatch>() .AddTransient<CloudWatchWrapper>() ) .Build(); _configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json") // Load settings from .json file. .AddJsonFile("settings.local.json", true) // Optionally, load local settings. .Build(); logger = LoggerFactory.Create(builder => { builder.AddConsole(); }) .CreateLogger<CloudWatchScenario>(); _cloudWatchWrapper = host.Services.GetRequiredService<CloudWatchWrapper>(); Console.WriteLine(new string('-', 80)); Console.WriteLine("Welcome to the Amazon CloudWatch example scenario."); Console.WriteLine(new string('-', 80)); try { var selectedNamespace = await SelectNamespace(); Learn the basics 2852 Amazon CloudWatch User Guide var selectedMetric = await SelectMetric(selectedNamespace); await GetAndDisplayMetricStatistics(selectedNamespace, selectedMetric); await GetAndDisplayEstimatedBilling(); await CreateDashboardWithMetrics(); await ListDashboards(); await CreateNewCustomMetric(); await AddMetricToDashboard(); await CreateMetricAlarm(); await DescribeAlarms(); await GetCustomMetricData(); await AddMetricDataForAlarm(); await CheckForMetricAlarm(); await GetAlarmHistory(); anomalyDetector = await AddAnomalyDetector(); await DescribeAnomalyDetectors(); await GetAndOpenMetricImage(); await CleanupResources(); } catch (Exception ex) { logger.LogError(ex, "There was a problem executing the scenario."); await CleanupResources(); } } /// <summary> /// Select a namespace.
acw-ug-815
acw-ug.pdf
815
LoggerFactory.Create(builder => { builder.AddConsole(); }) .CreateLogger<CloudWatchScenario>(); _cloudWatchWrapper = host.Services.GetRequiredService<CloudWatchWrapper>(); Console.WriteLine(new string('-', 80)); Console.WriteLine("Welcome to the Amazon CloudWatch example scenario."); Console.WriteLine(new string('-', 80)); try { var selectedNamespace = await SelectNamespace(); Learn the basics 2852 Amazon CloudWatch User Guide var selectedMetric = await SelectMetric(selectedNamespace); await GetAndDisplayMetricStatistics(selectedNamespace, selectedMetric); await GetAndDisplayEstimatedBilling(); await CreateDashboardWithMetrics(); await ListDashboards(); await CreateNewCustomMetric(); await AddMetricToDashboard(); await CreateMetricAlarm(); await DescribeAlarms(); await GetCustomMetricData(); await AddMetricDataForAlarm(); await CheckForMetricAlarm(); await GetAlarmHistory(); anomalyDetector = await AddAnomalyDetector(); await DescribeAnomalyDetectors(); await GetAndOpenMetricImage(); await CleanupResources(); } catch (Exception ex) { logger.LogError(ex, "There was a problem executing the scenario."); await CleanupResources(); } } /// <summary> /// Select a namespace. /// </summary> /// <returns>The selected namespace.</returns> private static async Task<string> SelectNamespace() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"1. Select a CloudWatch Namespace from a list of Namespaces."); var metrics = await _cloudWatchWrapper.ListMetrics(); // Get a distinct list of namespaces. var namespaces = metrics.Select(m => m.Namespace).Distinct().ToList(); for (int i = 0; i < namespaces.Count; i++) { Console.WriteLine($"\t{i + 1}. {namespaces[i]}"); } Learn the basics 2853 Amazon CloudWatch User Guide var namespaceChoiceNumber = 0; while (namespaceChoiceNumber < 1 || namespaceChoiceNumber > namespaces.Count) { Console.WriteLine( "Select a namespace by entering a number from the preceding list:"); var choice = Console.ReadLine(); Int32.TryParse(choice, out namespaceChoiceNumber); } var selectedNamespace = namespaces[namespaceChoiceNumber - 1]; Console.WriteLine(new string('-', 80)); return selectedNamespace; } /// <summary> /// Select a metric from a namespace. /// </summary> /// <param name="metricNamespace">The namespace for metrics.</param> /// <returns>The metric name.</returns> private static async Task<Metric> SelectMetric(string metricNamespace) { Console.WriteLine(new string('-', 80)); Console.WriteLine($"2. Select a CloudWatch metric from a namespace."); var namespaceMetrics = await _cloudWatchWrapper.ListMetrics(metricNamespace); for (int i = 0; i < namespaceMetrics.Count && i < 15; i++) { var dimensionsWithValues = namespaceMetrics[i].Dimensions .Where(d => !string.Equals("None", d.Value)); Console.WriteLine($"\t{i + 1}. {namespaceMetrics[i].MetricName} " + $"{string.Join(", :", dimensionsWithValues.Select(d => d.Value))}"); } var metricChoiceNumber = 0; while (metricChoiceNumber < 1 || metricChoiceNumber > namespaceMetrics.Count) { Learn the basics 2854 Amazon CloudWatch User Guide Console.WriteLine( "Select a metric by entering a number from the preceding list:"); var choice = Console.ReadLine(); Int32.TryParse(choice, out metricChoiceNumber); } var selectedMetric = namespaceMetrics[metricChoiceNumber - 1]; Console.WriteLine(new string('-', 80)); return selectedMetric; } /// <summary> /// Get and display metric statistics for a specific metric. /// </summary> /// <param name="metricNamespace">The namespace for metrics.</param> /// <param name="metric">The CloudWatch metric.</param> /// <returns>Async task.</returns> private static async Task GetAndDisplayMetricStatistics(string metricNamespace, Metric metric) { Console.WriteLine(new string('-', 80)); Console.WriteLine($"3. Get CloudWatch metric statistics for the last day."); for (int i = 0; i < _statTypes.Count; i++) { Console.WriteLine($"\t{i + 1}. {_statTypes[i]}"); } var statisticChoiceNumber = 0; while (statisticChoiceNumber < 1 || statisticChoiceNumber > _statTypes.Count) { Console.WriteLine( "Select a metric statistic by entering a number from the preceding list:"); var choice = Console.ReadLine(); Int32.TryParse(choice, out statisticChoiceNumber); } var selectedStatistic = _statTypes[statisticChoiceNumber - 1]; var statisticsList = new List<string> { selectedStatistic }; Learn the basics 2855 Amazon CloudWatch User Guide var metricStatistics = await _cloudWatchWrapper.GetMetricStatistics(metricNamespace, metric.MetricName, statisticsList, metric.Dimensions, 1, 60); if (!metricStatistics.Any()) { Console.WriteLine($"No {selectedStatistic} statistics found for {metric} in namespace {metricNamespace}."); } metricStatistics = metricStatistics.OrderBy(s => s.Timestamp).ToList(); for (int i = 0; i < metricStatistics.Count && i < 10; i++) { var metricStat = metricStatistics[i]; var statValue = metricStat.GetType().GetProperty(selectedStatistic)!.GetValue(metricStat, null); Console.WriteLine($"\t{i + 1}. Timestamp {metricStatistics[i].Timestamp:G} {selectedStatistic}: {statValue}"); } Console.WriteLine(new string('-', 80)); } /// <summary> /// Get and display estimated billing statistics. /// </summary> /// <param name="metricNamespace">The namespace for metrics.</param> /// <param name="metric">The CloudWatch metric.</param> /// <returns>Async task.</returns> private static async Task GetAndDisplayEstimatedBilling() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"4. Get CloudWatch estimated billing for the last week."); var billingStatistics = await SetupBillingStatistics(); for (int i = 0; i < billingStatistics.Count; i++) { Console.WriteLine($"\t{i + 1}. Timestamp {billingStatistics[i].Timestamp:G} : {billingStatistics[i].Maximum}"); } Learn the basics 2856 Amazon CloudWatch User Guide Console.WriteLine(new string('-', 80)); } /// <summary> /// Get billing statistics using a call to a wrapper class. /// </summary> /// <returns>A collection of billing statistics.</returns> private static async Task<List<Datapoint>> SetupBillingStatistics() { // Make a request for EstimatedCharges with a period of one day for the past seven days. var billingStatistics = await _cloudWatchWrapper.GetMetricStatistics( "AWS/Billing", "EstimatedCharges", new List<string>() { "Maximum" }, new List<Dimension>() { new Dimension { Name = "Currency", Value = "USD" } }, 7, 86400); billingStatistics = billingStatistics.OrderBy(n => n.Timestamp).ToList(); return billingStatistics; } /// <summary> /// Create a dashboard with metrics. /// </summary> /// <param name="metricNamespace">The namespace for metrics.</param> /// <param name="metric">The CloudWatch metric.</param> /// <returns>Async task.</returns> private static async Task CreateDashboardWithMetrics() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"5. Create a new CloudWatch dashboard with metrics."); var dashboardName = _configuration["dashboardName"]; var newDashboard = new DashboardModel(); _configuration.GetSection("dashboardExampleBody").Bind(newDashboard); var newDashboardString = JsonSerializer.Serialize( newDashboard, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }); Learn the basics 2857 Amazon CloudWatch User Guide var validationMessages = await _cloudWatchWrapper.PutDashboard(dashboardName, newDashboardString); Console.WriteLine(validationMessages.Any() ? $"\tValidation messages:" : null); for (int i = 0; i < validationMessages.Count; i++) { Console.WriteLine($"\t{i + 1}. {validationMessages[i].Message}"); } Console.WriteLine($"\tDashboard {dashboardName} was created."); Console.WriteLine(new string('-', 80)); } /// <summary> /// List dashboards. /// </summary> /// <returns>Async task.</returns> private
acw-ug-816
acw-ug.pdf
816
<param name="metric">The CloudWatch metric.</param> /// <returns>Async task.</returns> private static async Task CreateDashboardWithMetrics() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"5. Create a new CloudWatch dashboard with metrics."); var dashboardName = _configuration["dashboardName"]; var newDashboard = new DashboardModel(); _configuration.GetSection("dashboardExampleBody").Bind(newDashboard); var newDashboardString = JsonSerializer.Serialize( newDashboard, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }); Learn the basics 2857 Amazon CloudWatch User Guide var validationMessages = await _cloudWatchWrapper.PutDashboard(dashboardName, newDashboardString); Console.WriteLine(validationMessages.Any() ? $"\tValidation messages:" : null); for (int i = 0; i < validationMessages.Count; i++) { Console.WriteLine($"\t{i + 1}. {validationMessages[i].Message}"); } Console.WriteLine($"\tDashboard {dashboardName} was created."); Console.WriteLine(new string('-', 80)); } /// <summary> /// List dashboards. /// </summary> /// <returns>Async task.</returns> private static async Task ListDashboards() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"6. List the CloudWatch dashboards in the current account."); var dashboards = await _cloudWatchWrapper.ListDashboards(); for (int i = 0; i < dashboards.Count; i++) { Console.WriteLine($"\t{i + 1}. {dashboards[i].DashboardName}"); } Console.WriteLine(new string('-', 80)); } /// <summary> /// Create and add data for a new custom metric. /// </summary> /// <returns>Async task.</returns> private static async Task CreateNewCustomMetric() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"7. Create and add data for a new custom metric."); var customMetricNamespace = _configuration["customMetricNamespace"]; Learn the basics 2858 Amazon CloudWatch User Guide var customMetricName = _configuration["customMetricName"]; var customData = await PutRandomMetricData(customMetricName, customMetricNamespace); var valuesString = string.Join(',', customData.Select(d => d.Value)); Console.WriteLine($"\tAdded metric values for for metric {customMetricName}: \n\t{valuesString}"); Console.WriteLine(new string('-', 80)); } /// <summary> /// Add some metric data using a call to a wrapper class. /// </summary> /// <param name="customMetricName">The metric name.</param> /// <param name="customMetricNamespace">The metric namespace.</param> /// <returns></returns> private static async Task<List<MetricDatum>> PutRandomMetricData(string customMetricName, string customMetricNamespace) { List<MetricDatum> customData = new List<MetricDatum>(); Random rnd = new Random(); // Add 10 random values up to 100, starting with a timestamp 15 minutes in the past. var utcNowMinus15 = DateTime.UtcNow.AddMinutes(-15); for (int i = 0; i < 10; i++) { var metricValue = rnd.Next(0, 100); customData.Add( new MetricDatum { MetricName = customMetricName, Value = metricValue, TimestampUtc = utcNowMinus15.AddMinutes(i) } ); } await _cloudWatchWrapper.PutMetricData(customMetricNamespace, customData); Learn the basics 2859 Amazon CloudWatch User Guide return customData; } /// <summary> /// Add the custom metric to the dashboard. /// </summary> /// <returns>Async task.</returns> private static async Task AddMetricToDashboard() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"8. Add the new custom metric to the dashboard."); var dashboardName = _configuration["dashboardName"]; var customMetricNamespace = _configuration["customMetricNamespace"]; var customMetricName = _configuration["customMetricName"]; var validationMessages = await SetupDashboard(customMetricNamespace, customMetricName, dashboardName); Console.WriteLine(validationMessages.Any() ? $"\tValidation messages:" : null); for (int i = 0; i < validationMessages.Count; i++) { Console.WriteLine($"\t{i + 1}. {validationMessages[i].Message}"); } Console.WriteLine($"\tDashboard {dashboardName} updated with metric {customMetricName}."); Console.WriteLine(new string('-', 80)); } /// <summary> /// Set up a dashboard using a call to the wrapper class. /// </summary> /// <param name="customMetricNamespace">The metric namespace.</param> /// <param name="customMetricName">The metric name.</param> /// <param name="dashboardName">The name of the dashboard.</param> /// <returns>A list of validation messages.</returns> private static async Task<List<DashboardValidationMessage>> SetupDashboard( string customMetricNamespace, string customMetricName, string dashboardName) { // Get the dashboard model from configuration. Learn the basics 2860 Amazon CloudWatch User Guide var newDashboard = new DashboardModel(); _configuration.GetSection("dashboardExampleBody").Bind(newDashboard); // Add a new metric to the dashboard. newDashboard.Widgets.Add(new Widget { Height = 8, Width = 8, Y = 8, X = 0, Type = "metric", Properties = new Properties { Metrics = new List<List<object>> { new() { customMetricNamespace, customMetricName } }, View = "timeSeries", Region = "us-east-1", Stat = "Sum", Period = 86400, YAxis = new YAxis { Left = new Left { Min = 0, Max = 100 } }, Title = "Custom Metric Widget", LiveData = true, Sparkline = true, Trend = true, Stacked = false, SetPeriodToTimeRange = false } }); var newDashboardString = JsonSerializer.Serialize(newDashboard, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }); var validationMessages = await _cloudWatchWrapper.PutDashboard(dashboardName, newDashboardString); return validationMessages; } /// <summary> /// Create a CloudWatch alarm for the new metric. /// </summary> /// <returns>Async task.</returns> private static async Task CreateMetricAlarm() Learn the basics 2861 Amazon CloudWatch { User Guide Console.WriteLine(new string('-', 80)); Console.WriteLine($"9. Create a CloudWatch alarm for the new metric."); var customMetricNamespace = _configuration["customMetricNamespace"]; var customMetricName = _configuration["customMetricName"]; var alarmName = _configuration["exampleAlarmName"]; var accountId = _configuration["accountId"]; var region = _configuration["region"]; var emailTopic = _configuration["emailTopic"]; var alarmActions = new List<string>(); if (GetYesNoResponse( $"\tAdd an email action for topic {emailTopic} to alarm {alarmName}? (y/n)")) { _cloudWatchWrapper.AddEmailAlarmAction(accountId, region, emailTopic, alarmActions); } await _cloudWatchWrapper.PutMetricEmailAlarm( "Example metric alarm", alarmName, ComparisonOperator.GreaterThanOrEqualToThreshold, customMetricName, customMetricNamespace, 100, alarmActions); Console.WriteLine($"\tAlarm {alarmName} added for metric {customMetricName}."); Console.WriteLine(new string('-', 80)); } /// <summary> /// Describe Alarms. /// </summary> /// <returns>Async task.</returns> private static async Task DescribeAlarms() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"10. Describe CloudWatch alarms in the current account."); Learn the basics 2862 Amazon CloudWatch User Guide var alarms = await _cloudWatchWrapper.DescribeAlarms(); alarms = alarms.OrderByDescending(a => a.StateUpdatedTimestamp).ToList(); for (int i = 0; i < alarms.Count && i < 10; i++) { var alarm = alarms[i]; Console.WriteLine($"\t{i + 1}. {alarm.AlarmName}"); Console.WriteLine($"\tState: {alarm.StateValue} for {alarm.MetricName} {alarm.ComparisonOperator} {alarm.Threshold}"); } Console.WriteLine(new string('-', 80)); } /// <summary> /// Get the recent data for the metric. ///
acw-ug-817
acw-ug.pdf
817
alarmActions); Console.WriteLine($"\tAlarm {alarmName} added for metric {customMetricName}."); Console.WriteLine(new string('-', 80)); } /// <summary> /// Describe Alarms. /// </summary> /// <returns>Async task.</returns> private static async Task DescribeAlarms() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"10. Describe CloudWatch alarms in the current account."); Learn the basics 2862 Amazon CloudWatch User Guide var alarms = await _cloudWatchWrapper.DescribeAlarms(); alarms = alarms.OrderByDescending(a => a.StateUpdatedTimestamp).ToList(); for (int i = 0; i < alarms.Count && i < 10; i++) { var alarm = alarms[i]; Console.WriteLine($"\t{i + 1}. {alarm.AlarmName}"); Console.WriteLine($"\tState: {alarm.StateValue} for {alarm.MetricName} {alarm.ComparisonOperator} {alarm.Threshold}"); } Console.WriteLine(new string('-', 80)); } /// <summary> /// Get the recent data for the metric. /// </summary> /// <returns>Async task.</returns> private static async Task GetCustomMetricData() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"11. Get current data for new custom metric."); var customMetricNamespace = _configuration["customMetricNamespace"]; var customMetricName = _configuration["customMetricName"]; var accountId = _configuration["accountId"]; var query = new List<MetricDataQuery> { new MetricDataQuery { AccountId = accountId, Id = "m1", Label = "Custom Metric Data", MetricStat = new MetricStat { Metric = new Metric { MetricName = customMetricName, Namespace = customMetricNamespace, }, Period = 1, Stat = "Maximum" Learn the basics 2863 Amazon CloudWatch User Guide } } }; var metricData = await _cloudWatchWrapper.GetMetricData( 20, true, DateTime.UtcNow.AddMinutes(1), 20, query); for (int i = 0; i < metricData.Count; i++) { for (int j = 0; j < metricData[i].Values.Count; j++) { Console.WriteLine( $"\tTimestamp {metricData[i].Timestamps[j]:G} Value: {metricData[i].Values[j]}"); } } Console.WriteLine(new string('-', 80)); } /// <summary> /// Add metric data to trigger an alarm. /// </summary> /// <returns>Async task.</returns> private static async Task AddMetricDataForAlarm() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"12. Add metric data to the custom metric to trigger an alarm."); var customMetricNamespace = _configuration["customMetricNamespace"]; var customMetricName = _configuration["customMetricName"]; var nowUtc = DateTime.UtcNow; List<MetricDatum> customData = new List<MetricDatum> { new MetricDatum { MetricName = customMetricName, Value = 101, TimestampUtc = nowUtc.AddMinutes(-2) Learn the basics 2864 Amazon CloudWatch User Guide }, new MetricDatum { MetricName = customMetricName, Value = 101, TimestampUtc = nowUtc.AddMinutes(-1) }, new MetricDatum { MetricName = customMetricName, Value = 101, TimestampUtc = nowUtc } }; var valuesString = string.Join(',', customData.Select(d => d.Value)); Console.WriteLine($"\tAdded metric values for for metric {customMetricName}: \n\t{valuesString}"); await _cloudWatchWrapper.PutMetricData(customMetricNamespace, customData); Console.WriteLine(new string('-', 80)); } /// <summary> /// Check for a metric alarm using the DescribeAlarmsForMetric action. /// </summary> /// <returns>Async task.</returns> private static async Task CheckForMetricAlarm() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"13. Checking for an alarm state."); var customMetricNamespace = _configuration["customMetricNamespace"]; var customMetricName = _configuration["customMetricName"]; var hasAlarm = false; var retries = 10; while (!hasAlarm && retries > 0) { var alarms = await _cloudWatchWrapper.DescribeAlarmsForMetric(customMetricNamespace, customMetricName); hasAlarm = alarms.Any(a => a.StateValue == StateValue.ALARM); retries--; Thread.Sleep(20000); Learn the basics 2865 Amazon CloudWatch } User Guide Console.WriteLine(hasAlarm ? $"\tAlarm state found for {customMetricName}." : $"\tNo Alarm state found for {customMetricName} after 10 retries."); Console.WriteLine(new string('-', 80)); } /// <summary> /// Get history for an alarm. /// </summary> /// <returns>Async task.</returns> private static async Task GetAlarmHistory() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"14. Get alarm history."); var exampleAlarmName = _configuration["exampleAlarmName"]; var alarmHistory = await _cloudWatchWrapper.DescribeAlarmHistory(exampleAlarmName, 2); for (int i = 0; i < alarmHistory.Count; i++) { var history = alarmHistory[i]; Console.WriteLine($"\t{i + 1}. {history.HistorySummary}, time {history.Timestamp:g}"); } if (!alarmHistory.Any()) { Console.WriteLine($"\tNo alarm history data found for {exampleAlarmName}."); } Console.WriteLine(new string('-', 80)); } /// <summary> /// Add an anomaly detector. /// </summary> /// <returns>Async task.</returns> private static async Task<SingleMetricAnomalyDetector> AddAnomalyDetector() Learn the basics 2866 Amazon CloudWatch { User Guide Console.WriteLine(new string('-', 80)); Console.WriteLine($"15. Add an anomaly detector."); var customMetricNamespace = _configuration["customMetricNamespace"]; var customMetricName = _configuration["customMetricName"]; var detector = new SingleMetricAnomalyDetector { MetricName = customMetricName, Namespace = customMetricNamespace, Stat = "Maximum" }; await _cloudWatchWrapper.PutAnomalyDetector(detector); Console.WriteLine($"\tAdded anomaly detector for metric {customMetricName}."); Console.WriteLine(new string('-', 80)); return detector; } /// <summary> /// Describe anomaly detectors. /// </summary> /// <returns>Async task.</returns> private static async Task DescribeAnomalyDetectors() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"16. Describe anomaly detectors in the current account."); var customMetricNamespace = _configuration["customMetricNamespace"]; var customMetricName = _configuration["customMetricName"]; var detectors = await _cloudWatchWrapper.DescribeAnomalyDetectors(customMetricNamespace, customMetricName); for (int i = 0; i < detectors.Count; i++) { var detector = detectors[i]; Console.WriteLine($"\t{i + 1}. {detector.SingleMetricAnomalyDetector.MetricName}, state {detector.StateValue}"); Learn the basics 2867 Amazon CloudWatch } User Guide Console.WriteLine(new string('-', 80)); } /// <summary> /// Fetch and open a metrics image for a CloudWatch metric and namespace. /// </summary> /// <returns>Async task.</returns> private static async Task GetAndOpenMetricImage() { Console.WriteLine(new string('-', 80)); Console.WriteLine("17. Get a metric image from CloudWatch."); Console.WriteLine($"\tGetting Image data for custom metric."); var customMetricNamespace = _configuration["customMetricNamespace"]; var customMetricName = _configuration["customMetricName"]; var memoryStream = await _cloudWatchWrapper.GetTimeSeriesMetricImage(customMetricNamespace, customMetricName, "Maximum", 10); var file = _cloudWatchWrapper.SaveMetricImage(memoryStream, "MetricImages"); ProcessStartInfo info = new ProcessStartInfo(); Console.WriteLine($"\tFile saved as {Path.GetFileName(file)}."); Console.WriteLine($"\tPress enter to open the image."); Console.ReadLine(); info.FileName = Path.Combine("ms-photos://", file); info.UseShellExecute = true; info.CreateNoWindow = true; info.Verb = string.Empty; Process.Start(info); Console.WriteLine(new string('-', 80)); } /// <summary> /// Clean up created resources. /// </summary> /// <param name="metricNamespace">The namespace for metrics.</param> /// <param name="metric">The CloudWatch metric.</param> Learn the basics 2868 Amazon CloudWatch User Guide /// <returns>Async task.</returns> private
acw-ug-818
acw-ug.pdf
818
Console.WriteLine("17. Get a metric image from CloudWatch."); Console.WriteLine($"\tGetting Image data for custom metric."); var customMetricNamespace = _configuration["customMetricNamespace"]; var customMetricName = _configuration["customMetricName"]; var memoryStream = await _cloudWatchWrapper.GetTimeSeriesMetricImage(customMetricNamespace, customMetricName, "Maximum", 10); var file = _cloudWatchWrapper.SaveMetricImage(memoryStream, "MetricImages"); ProcessStartInfo info = new ProcessStartInfo(); Console.WriteLine($"\tFile saved as {Path.GetFileName(file)}."); Console.WriteLine($"\tPress enter to open the image."); Console.ReadLine(); info.FileName = Path.Combine("ms-photos://", file); info.UseShellExecute = true; info.CreateNoWindow = true; info.Verb = string.Empty; Process.Start(info); Console.WriteLine(new string('-', 80)); } /// <summary> /// Clean up created resources. /// </summary> /// <param name="metricNamespace">The namespace for metrics.</param> /// <param name="metric">The CloudWatch metric.</param> Learn the basics 2868 Amazon CloudWatch User Guide /// <returns>Async task.</returns> private static async Task CleanupResources() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"18. Clean up resources."); var dashboardName = _configuration["dashboardName"]; if (GetYesNoResponse($"\tDelete dashboard {dashboardName}? (y/n)")) { Console.WriteLine($"\tDeleting dashboard."); var dashboardList = new List<string> { dashboardName }; await _cloudWatchWrapper.DeleteDashboards(dashboardList); } var alarmName = _configuration["exampleAlarmName"]; if (GetYesNoResponse($"\tDelete alarm {alarmName}? (y/n)")) { Console.WriteLine($"\tCleaning up alarms."); var alarms = new List<string> { alarmName }; await _cloudWatchWrapper.DeleteAlarms(alarms); } if (GetYesNoResponse($"\tDelete anomaly detector? (y/n)") && anomalyDetector != null) { Console.WriteLine($"\tCleaning up anomaly detector."); await _cloudWatchWrapper.DeleteAnomalyDetector( anomalyDetector); } Console.WriteLine(new string('-', 80)); } /// <summary> /// Get a yes or no response from the user. /// </summary> /// <param name="question">The question string to print on the console.</ param> /// <returns>True if the user responds with a yes.</returns> private static bool GetYesNoResponse(string question) { Console.WriteLine(question); var ynResponse = Console.ReadLine(); Learn the basics 2869 Amazon CloudWatch User Guide var response = ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase); return response; } } Wrapper methods used by the scenario for CloudWatch actions. /// <summary> /// Wrapper class for Amazon CloudWatch methods. /// </summary> public class CloudWatchWrapper { private readonly IAmazonCloudWatch _amazonCloudWatch; private readonly ILogger<CloudWatchWrapper> _logger; /// <summary> /// Constructor for the CloudWatch wrapper. /// </summary> /// <param name="amazonCloudWatch">The injected CloudWatch client.</param> /// <param name="logger">The injected logger for the wrapper.</param> public CloudWatchWrapper(IAmazonCloudWatch amazonCloudWatch, ILogger<CloudWatchWrapper> logger) { _logger = logger; _amazonCloudWatch = amazonCloudWatch; } /// <summary> /// List metrics available, optionally within a namespace. /// </summary> /// <param name="metricNamespace">Optional CloudWatch namespace to use when listing metrics.</param> /// <param name="filter">Optional dimension filter.</param> /// <param name="metricName">Optional metric name filter.</param> /// <returns>The list of metrics.</returns> public async Task<List<Metric>> ListMetrics(string? metricNamespace = null, DimensionFilter? filter = null, string? metricName = null) { var results = new List<Metric>(); Learn the basics 2870 Amazon CloudWatch User Guide var paginateMetrics = _amazonCloudWatch.Paginators.ListMetrics( new ListMetricsRequest { Namespace = metricNamespace, Dimensions = filter != null ? new List<DimensionFilter> { filter } : null, MetricName = metricName }); // Get the entire list using the paginator. await foreach (var metric in paginateMetrics.Metrics) { results.Add(metric); } return results; } /// <summary> /// Wrapper to get statistics for a specific CloudWatch metric. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricName">The name of the metric.</param> /// <param name="statistics">The list of statistics to include.</param> /// <param name="dimensions">The list of dimensions to include.</param> /// <param name="days">The number of days in the past to include.</param> /// <param name="period">The period for the data.</param> /// <returns>A list of DataPoint objects for the statistics.</returns> public async Task<List<Datapoint>> GetMetricStatistics(string metricNamespace, string metricName, List<string> statistics, List<Dimension> dimensions, int days, int period) { var metricStatistics = await _amazonCloudWatch.GetMetricStatisticsAsync( new GetMetricStatisticsRequest() { Namespace = metricNamespace, MetricName = metricName, Dimensions = dimensions, Statistics = statistics, StartTimeUtc = DateTime.UtcNow.AddDays(-days), EndTimeUtc = DateTime.UtcNow, Period = period }); Learn the basics 2871 Amazon CloudWatch User Guide return metricStatistics.Datapoints; } /// <summary> /// Wrapper to create or add to a dashboard with metrics. /// </summary> /// <param name="dashboardName">The name for the dashboard.</param> /// <param name="dashboardBody">The metric data in JSON for the dashboard.</ param> /// <returns>A list of validation messages for the dashboard.</returns> public async Task<List<DashboardValidationMessage>> PutDashboard(string dashboardName, string dashboardBody) { // Updating a dashboard replaces all contents. // Best practice is to include a text widget indicating this dashboard was created programmatically. var dashboardResponse = await _amazonCloudWatch.PutDashboardAsync( new PutDashboardRequest() { DashboardName = dashboardName, DashboardBody = dashboardBody }); return dashboardResponse.DashboardValidationMessages; } /// <summary> /// Get information on a dashboard. /// </summary> /// <param name="dashboardName">The name of the dashboard.</param> /// <returns>A JSON object with dashboard information.</returns> public async Task<string> GetDashboard(string dashboardName) { var dashboardResponse = await _amazonCloudWatch.GetDashboardAsync( new GetDashboardRequest() { DashboardName = dashboardName }); return dashboardResponse.DashboardBody; } Learn the basics 2872 Amazon CloudWatch User Guide /// <summary> /// Get a list of dashboards. /// </summary> /// <returns>A list of DashboardEntry objects.</returns> public async Task<List<DashboardEntry>> ListDashboards() { var results = new List<DashboardEntry>(); var paginateDashboards = _amazonCloudWatch.Paginators.ListDashboards( new ListDashboardsRequest()); // Get the entire list using the paginator. await foreach (var data in paginateDashboards.DashboardEntries) { results.Add(data); } return results; } /// <summary> /// Wrapper to add metric data to a CloudWatch metric. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricData">A data object for the metric data.</param> /// <returns>True if successful.</returns> public async Task<bool> PutMetricData(string metricNamespace, List<MetricDatum> metricData) { var putDataResponse = await _amazonCloudWatch.PutMetricDataAsync(
acw-ug-819
acw-ug.pdf
819
Guide /// <summary> /// Get a list of dashboards. /// </summary> /// <returns>A list of DashboardEntry objects.</returns> public async Task<List<DashboardEntry>> ListDashboards() { var results = new List<DashboardEntry>(); var paginateDashboards = _amazonCloudWatch.Paginators.ListDashboards( new ListDashboardsRequest()); // Get the entire list using the paginator. await foreach (var data in paginateDashboards.DashboardEntries) { results.Add(data); } return results; } /// <summary> /// Wrapper to add metric data to a CloudWatch metric. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricData">A data object for the metric data.</param> /// <returns>True if successful.</returns> public async Task<bool> PutMetricData(string metricNamespace, List<MetricDatum> metricData) { var putDataResponse = await _amazonCloudWatch.PutMetricDataAsync( new PutMetricDataRequest() { MetricData = metricData, Namespace = metricNamespace, }); return putDataResponse.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Get an image for a metric graphed over time. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metric">The name of the metric.</param> /// <param name="stat">The name of the stat to chart.</param> Learn the basics 2873 Amazon CloudWatch User Guide /// <param name="period">The period to use for the chart.</param> /// <returns>A memory stream for the chart image.</returns> public async Task<MemoryStream> GetTimeSeriesMetricImage(string metricNamespace, string metric, string stat, int period) { var metricImageWidget = new { title = "Example Metric Graph", view = "timeSeries", stacked = false, period = period, width = 1400, height = 600, metrics = new List<List<object>> { new() { metricNamespace, metric, new { stat } } } }; var metricImageWidgetString = JsonSerializer.Serialize(metricImageWidget); var imageResponse = await _amazonCloudWatch.GetMetricWidgetImageAsync( new GetMetricWidgetImageRequest() { MetricWidget = metricImageWidgetString }); return imageResponse.MetricWidgetImage; } /// <summary> /// Save a metric image to a file. /// </summary> /// <param name="memoryStream">The MemoryStream for the metric image.</param> /// <param name="metricName">The name of the metric.</param> /// <returns>The path to the file.</returns> public string SaveMetricImage(MemoryStream memoryStream, string metricName) { var metricFileName = $"{metricName}_{DateTime.Now.Ticks}.png"; using var sr = new StreamReader(memoryStream); // Writes the memory stream to a file. File.WriteAllBytes(metricFileName, memoryStream.ToArray()); var filePath = Path.Join(AppDomain.CurrentDomain.BaseDirectory, metricFileName); return filePath; } Learn the basics 2874 Amazon CloudWatch User Guide /// <summary> /// Get data for CloudWatch metrics. /// </summary> /// <param name="minutesOfData">The number of minutes of data to include.</ param> /// <param name="useDescendingTime">True to return the data descending by time.</param> /// <param name="endDateUtc">The end date for the data, in UTC.</param> /// <param name="maxDataPoints">The maximum data points to include.</param> /// <param name="dataQueries">Optional data queries to include.</param> /// <returns>A list of the requested metric data.</returns> public async Task<List<MetricDataResult>> GetMetricData(int minutesOfData, bool useDescendingTime, DateTime? endDateUtc = null, int maxDataPoints = 0, List<MetricDataQuery>? dataQueries = null) { var metricData = new List<MetricDataResult>(); // If no end time is provided, use the current time for the end time. endDateUtc ??= DateTime.UtcNow; var timeZoneOffset = TimeZoneInfo.Local.GetUtcOffset(endDateUtc.Value.ToLocalTime()); var startTimeUtc = endDateUtc.Value.AddMinutes(-minutesOfData); // The timezone string should be in the format +0000, so use the timezone offset to format it correctly. var timeZoneString = $"{timeZoneOffset.Hours:D2} {timeZoneOffset.Minutes:D2}"; var paginatedMetricData = _amazonCloudWatch.Paginators.GetMetricData( new GetMetricDataRequest() { StartTimeUtc = startTimeUtc, EndTimeUtc = endDateUtc.Value, LabelOptions = new LabelOptions { Timezone = timeZoneString }, ScanBy = useDescendingTime ? ScanBy.TimestampDescending : ScanBy.TimestampAscending, MaxDatapoints = maxDataPoints, MetricDataQueries = dataQueries, }); await foreach (var data in paginatedMetricData.MetricDataResults) { metricData.Add(data); } return metricData; } Learn the basics 2875 Amazon CloudWatch User Guide /// <summary> /// Add a metric alarm to send an email when the metric passes a threshold. /// </summary> /// <param name="alarmDescription">A description of the alarm.</param> /// <param name="alarmName">The name for the alarm.</param> /// <param name="comparison">The type of comparison to use.</param> /// <param name="metricName">The name of the metric for the alarm.</param> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="threshold">The threshold value for the alarm.</param> /// <param name="alarmActions">Optional actions to execute when in an alarm state.</param> /// <returns>True if successful.</returns> public async Task<bool> PutMetricEmailAlarm(string alarmDescription, string alarmName, ComparisonOperator comparison, string metricName, string metricNamespace, double threshold, List<string> alarmActions = null!) { try { var putEmailAlarmResponse = await _amazonCloudWatch.PutMetricAlarmAsync( new PutMetricAlarmRequest() { AlarmActions = alarmActions, AlarmDescription = alarmDescription, AlarmName = alarmName, ComparisonOperator = comparison, Threshold = threshold, Namespace = metricNamespace, MetricName = metricName, EvaluationPeriods = 1, Period = 10, Statistic = new Statistic("Maximum"), DatapointsToAlarm = 1, TreatMissingData = "ignore" }); return putEmailAlarmResponse.HttpStatusCode == HttpStatusCode.OK; } catch (LimitExceededException lex) { _logger.LogError(lex, $"Unable to add alarm {alarmName}. Alarm quota has already been reached."); } Learn the basics 2876 Amazon CloudWatch User Guide return false; } /// <summary> /// Add specific email actions to a list of action strings for a CloudWatch alarm. /// </summary> /// <param name="accountId">The AccountId for the alarm.</param> /// <param name="region">The region for the alarm.</param> /// <param name="emailTopicName">An Amazon Simple Notification Service (SNS) topic for the alarm email.</param> /// <param name="alarmActions">Optional list of existing alarm actions to append to.</param> /// <returns>A list of string actions for an alarm.</returns> public List<string> AddEmailAlarmAction(string accountId, string region, string emailTopicName, List<string>? alarmActions = null) { alarmActions ??= new List<string>(); var snsAlarmAction = $"arn:aws:sns:{region}:{accountId}: {emailTopicName}"; alarmActions.Add(snsAlarmAction); return alarmActions; } /// <summary> /// Describe the current
acw-ug-820
acw-ug.pdf
820
false; } /// <summary> /// Add specific email actions to a list of action strings for a CloudWatch alarm. /// </summary> /// <param name="accountId">The AccountId for the alarm.</param> /// <param name="region">The region for the alarm.</param> /// <param name="emailTopicName">An Amazon Simple Notification Service (SNS) topic for the alarm email.</param> /// <param name="alarmActions">Optional list of existing alarm actions to append to.</param> /// <returns>A list of string actions for an alarm.</returns> public List<string> AddEmailAlarmAction(string accountId, string region, string emailTopicName, List<string>? alarmActions = null) { alarmActions ??= new List<string>(); var snsAlarmAction = $"arn:aws:sns:{region}:{accountId}: {emailTopicName}"; alarmActions.Add(snsAlarmAction); return alarmActions; } /// <summary> /// Describe the current alarms, optionally filtered by state. /// </summary> /// <param name="stateValue">Optional filter for alarm state.</param> /// <returns>The list of alarm data.</returns> public async Task<List<MetricAlarm>> DescribeAlarms(StateValue? stateValue = null) { List<MetricAlarm> alarms = new List<MetricAlarm>(); var paginatedDescribeAlarms = _amazonCloudWatch.Paginators.DescribeAlarms( new DescribeAlarmsRequest() { StateValue = stateValue }); await foreach (var data in paginatedDescribeAlarms.MetricAlarms) { alarms.Add(data); Learn the basics 2877 Amazon CloudWatch User Guide } return alarms; } /// <summary> /// Describe the current alarms for a specific metric. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricName">The name of the metric.</param> /// <returns>The list of alarm data.</returns> public async Task<List<MetricAlarm>> DescribeAlarmsForMetric(string metricNamespace, string metricName) { var alarmsResult = await _amazonCloudWatch.DescribeAlarmsForMetricAsync( new DescribeAlarmsForMetricRequest() { Namespace = metricNamespace, MetricName = metricName }); return alarmsResult.MetricAlarms; } /// <summary> /// Describe the history of an alarm for a number of days in the past. /// </summary> /// <param name="alarmName">The name of the alarm.</param> /// <param name="historyDays">The number of days in the past.</param> /// <returns>The list of alarm history data.</returns> public async Task<List<AlarmHistoryItem>> DescribeAlarmHistory(string alarmName, int historyDays) { List<AlarmHistoryItem> alarmHistory = new List<AlarmHistoryItem>(); var paginatedAlarmHistory = _amazonCloudWatch.Paginators.DescribeAlarmHistory( new DescribeAlarmHistoryRequest() { AlarmName = alarmName, EndDateUtc = DateTime.UtcNow, HistoryItemType = HistoryItemType.StateUpdate, StartDateUtc = DateTime.UtcNow.AddDays(-historyDays) }); await foreach (var data in paginatedAlarmHistory.AlarmHistoryItems) Learn the basics 2878 Amazon CloudWatch { alarmHistory.Add(data); } return alarmHistory; } User Guide /// <summary> /// Delete a list of alarms from CloudWatch. /// </summary> /// <param name="alarmNames">A list of names of alarms to delete.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteAlarms(List<string> alarmNames) { var deleteAlarmsResult = await _amazonCloudWatch.DeleteAlarmsAsync( new DeleteAlarmsRequest() { AlarmNames = alarmNames }); return deleteAlarmsResult.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Disable the actions for a list of alarms from CloudWatch. /// </summary> /// <param name="alarmNames">A list of names of alarms.</param> /// <returns>True if successful.</returns> public async Task<bool> DisableAlarmActions(List<string> alarmNames) { var disableAlarmActionsResult = await _amazonCloudWatch.DisableAlarmActionsAsync( new DisableAlarmActionsRequest() { AlarmNames = alarmNames }); return disableAlarmActionsResult.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Enable the actions for a list of alarms from CloudWatch. /// </summary> /// <param name="alarmNames">A list of names of alarms.</param> /// <returns>True if successful.</returns> Learn the basics 2879 Amazon CloudWatch User Guide public async Task<bool> EnableAlarmActions(List<string> alarmNames) { var enableAlarmActionsResult = await _amazonCloudWatch.EnableAlarmActionsAsync( new EnableAlarmActionsRequest() { AlarmNames = alarmNames }); return enableAlarmActionsResult.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Add an anomaly detector for a single metric. /// </summary> /// <param name="anomalyDetector">A single metric anomaly detector.</param> /// <returns>True if successful.</returns> public async Task<bool> PutAnomalyDetector(SingleMetricAnomalyDetector anomalyDetector) { var putAlarmDetectorResult = await _amazonCloudWatch.PutAnomalyDetectorAsync( new PutAnomalyDetectorRequest() { SingleMetricAnomalyDetector = anomalyDetector }); return putAlarmDetectorResult.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Describe anomaly detectors for a metric and namespace. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricName">The metric of the anomaly detectors.</param> /// <returns>The list of detectors.</returns> public async Task<List<AnomalyDetector>> DescribeAnomalyDetectors(string metricNamespace, string metricName) { List<AnomalyDetector> detectors = new List<AnomalyDetector>(); var paginatedDescribeAnomalyDetectors = _amazonCloudWatch.Paginators.DescribeAnomalyDetectors( new DescribeAnomalyDetectorsRequest() { Learn the basics 2880 Amazon CloudWatch User Guide MetricName = metricName, Namespace = metricNamespace }); await foreach (var data in paginatedDescribeAnomalyDetectors.AnomalyDetectors) { detectors.Add(data); } return detectors; } /// <summary> /// Delete a single metric anomaly detector. /// </summary> /// <param name="anomalyDetector">The anomaly detector to delete.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteAnomalyDetector(SingleMetricAnomalyDetector anomalyDetector) { var deleteAnomalyDetectorResponse = await _amazonCloudWatch.DeleteAnomalyDetectorAsync( new DeleteAnomalyDetectorRequest() { SingleMetricAnomalyDetector = anomalyDetector }); return deleteAnomalyDetectorResponse.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Delete a list of CloudWatch dashboards. /// </summary> /// <param name="dashboardNames">List of dashboard names to delete.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteDashboards(List<string> dashboardNames) { var deleteDashboardsResponse = await _amazonCloudWatch.DeleteDashboardsAsync( new DeleteDashboardsRequest() { DashboardNames = dashboardNames }); Learn the basics 2881 Amazon CloudWatch User Guide return deleteDashboardsResponse.HttpStatusCode == HttpStatusCode.OK; } } • For API details, see the following topics in AWS SDK for .NET API Reference. • DeleteAlarms • DeleteAnomalyDetector • DeleteDashboards • DescribeAlarmHistory • DescribeAlarms • DescribeAlarmsForMetric • DescribeAnomalyDetectors • GetMetricData • GetMetricStatistics • GetMetricWidgetImage • ListMetrics • PutAnomalyDetector • PutDashboard • PutMetricAlarm • PutMetricData Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Run an interactive scenario demonstrating CloudWatch features. Learn the basics 2882 Amazon CloudWatch User Guide import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatch.model.DashboardInvalidInputErrorException; import software.amazon.awssdk.services.cloudwatch.model.DeleteAlarmsResponse;
acw-ug-821
acw-ug.pdf
821
} } • For API details, see the following topics in AWS SDK for .NET API Reference. • DeleteAlarms • DeleteAnomalyDetector • DeleteDashboards • DescribeAlarmHistory • DescribeAlarms • DescribeAlarmsForMetric • DescribeAnomalyDetectors • GetMetricData • GetMetricStatistics • GetMetricWidgetImage • ListMetrics • PutAnomalyDetector • PutDashboard • PutMetricAlarm • PutMetricData Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Run an interactive scenario demonstrating CloudWatch features. Learn the basics 2882 Amazon CloudWatch User Guide import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatch.model.DashboardInvalidInputErrorException; import software.amazon.awssdk.services.cloudwatch.model.DeleteAlarmsResponse; import software.amazon.awssdk.services.cloudwatch.model.DeleteAnomalyDetectorResponse; import software.amazon.awssdk.services.cloudwatch.model.DeleteDashboardsResponse; import software.amazon.awssdk.services.cloudwatch.model.Dimension; import software.amazon.awssdk.services.cloudwatch.model.GetMetricStatisticsResponse; import software.amazon.awssdk.services.cloudwatch.model.LimitExceededException; import software.amazon.awssdk.services.cloudwatch.model.PutDashboardResponse; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import java.util.concurrent.CompletableFuture; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html * * To enable billing metrics and statistics for this example, make sure billing * alerts are enabled for your account: * https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ monitor_estimated_charges_with_cloudwatch.html#turning_on_billing_metrics * * This Java code example performs the following tasks: * * 1. List available namespaces from Amazon CloudWatch. * 2. List available metrics within the selected Namespace. * 3. Get statistics for the selected metric over the last day. * 4. Get CloudWatch estimated billing for the last week. * 5. Create a new CloudWatch dashboard with metrics. * 6. List dashboards using a paginator. * 7. Create a new custom metric by adding data for it. Learn the basics 2883 Amazon CloudWatch User Guide * 8. Add the custom metric to the dashboard. * 9. Create an alarm for the custom metric. * 10. Describe current alarms. * 11. Get current data for the new custom metric. * 12. Push data into the custom metric to trigger the alarm. * 13. Check the alarm state using the action DescribeAlarmsForMetric. * 14. Get alarm history for the new alarm. * 15. Add an anomaly detector for the custom metric. * 16. Describe current anomaly detectors. * 17. Get a metric image for the custom metric. * 18. Clean up the Amazon CloudWatch resources. */ public class CloudWatchScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); static CloudWatchActions cwActions = new CloudWatchActions(); private static final Logger logger = LoggerFactory.getLogger(CloudWatchScenario.class); static Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws Throwable { final String usage = """ Usage: <myDate> <costDateWeek> <dashboardName> <dashboardJson> <dashboardAdd> <settings> <metricImage> \s Where: myDate - The start date to use to get metric statistics. (For example, 2023-01-11T18:35:24.00Z.)\s costDateWeek - The start date to use to get AWS/Billing statistics. (For example, 2023-01-11T18:35:24.00Z.)\s dashboardName - The name of the dashboard to create.\s dashboardJson - The location of a JSON file to use to create a dashboard. (See jsonWidgets.json in javav2/example_code/cloudwatch.)\s dashboardAdd - The location of a JSON file to use to update a dashboard. (See CloudDashboard.json in javav2/example_code/cloudwatch.)\s settings - The location of a JSON file from which various values are read. (See settings.json in javav2/example_code/cloudwatch.)\s metricImage - The location of a BMP file that is used to create a graph.\s """; Learn the basics 2884 Amazon CloudWatch User Guide if (args.length != 7) { logger.info(usage); return; } String myDate = args[0]; String costDateWeek = args[1]; String dashboardName = args[2]; String dashboardJson = args[3]; String dashboardAdd = args[4]; String settings = args[5]; String metricImage = args[6]; logger.info(DASHES); logger.info("Welcome to the Amazon CloudWatch Basics scenario."); logger.info(""" Amazon CloudWatch is a comprehensive monitoring and observability service provided by Amazon Web Services (AWS). It is designed to help you monitor your AWS resources, applications, and services, as well as on-premises resources, in real-time. CloudWatch collects and tracks various types of data, including metrics, logs, and events, from your AWS and on-premises resources. It allows you to set alarms and automatically respond to changes in your environment, enabling you to quickly identify and address issues before they impact your applications or services. With CloudWatch, you can gain visibility into your entire infrastructure, from the cloud to the edge, and use this information to make informed decisions and optimize your resource utilization. This scenario guides you through how to perform Amazon CloudWatch tasks by using the AWS SDK for Java v2. Let's get started... """); waitForInputToContinue(scanner); Learn the basics 2885 Amazon CloudWatch User Guide try { runScenario(myDate, costDateWeek, dashboardName, dashboardJson, dashboardAdd, settings, metricImage); } catch (RuntimeException e) { e.printStackTrace(); } logger.info(DASHES); } private static void runScenario(String myDate, String costDateWeek, String dashboardName, String dashboardJson, String dashboardAdd, String settings, String metricImage ) throws Throwable { Double dataPoint = Double.parseDouble("10.0"); logger.info(DASHES); logger.info(""" 1. List at least five available unique namespaces from Amazon CloudWatch. Select one from the list. """); String selectedNamespace; String selectedMetrics; int num; try { CompletableFuture<ArrayList<String>> future = cwActions.listNameSpacesAsync(); ArrayList<String> list =
acw-ug-822
acw-ug.pdf
822
CloudWatch tasks by using the AWS SDK for Java v2. Let's get started... """); waitForInputToContinue(scanner); Learn the basics 2885 Amazon CloudWatch User Guide try { runScenario(myDate, costDateWeek, dashboardName, dashboardJson, dashboardAdd, settings, metricImage); } catch (RuntimeException e) { e.printStackTrace(); } logger.info(DASHES); } private static void runScenario(String myDate, String costDateWeek, String dashboardName, String dashboardJson, String dashboardAdd, String settings, String metricImage ) throws Throwable { Double dataPoint = Double.parseDouble("10.0"); logger.info(DASHES); logger.info(""" 1. List at least five available unique namespaces from Amazon CloudWatch. Select one from the list. """); String selectedNamespace; String selectedMetrics; int num; try { CompletableFuture<ArrayList<String>> future = cwActions.listNameSpacesAsync(); ArrayList<String> list = future.join(); for (int z = 0; z < 5; z++) { int index = z + 1; logger.info(" " + index + ". {}", list.get(z)); } num = Integer.parseInt(scanner.nextLine()); if (1 <= num && num <= 5) { selectedNamespace = list.get(num - 1); } else { logger.info("You did not select a valid option."); return; } logger.info("You selected {}", selectedNamespace); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { Learn the basics 2886 Amazon CloudWatch User Guide logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: " + rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("2. List available metrics within the selected namespace."); logger.info(""" A metric is a measure of the performance or health of your AWS resources, applications, or custom resources. Metrics are the basic building blocks of CloudWatch and provide data points that represent a specific aspect of your system or application over time. Select a metric from the list. """); Dimension myDimension = null; try { CompletableFuture<ArrayList<String>> future = cwActions.listMetsAsync(selectedNamespace); ArrayList<String> metList = future.join(); logger.info("Metrics successfully retrieved. Total metrics: {}", metList.size()); for (int z = 0; z < 5; z++) { int index = z + 1; logger.info(" " + index + ". " + metList.get(z)); } num = Integer.parseInt(scanner.nextLine()); if (1 <= num && num <= 5) { selectedMetrics = metList.get(num - 1); } else { logger.info("You did not select a valid option."); return; } logger.info("You selected {}", selectedMetrics); } catch (RuntimeException rt) { Learn the basics 2887 Amazon CloudWatch User Guide Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } try { myDimension = cwActions.getSpecificMetAsync(selectedNamespace).join(); logger.info("Metric statistics successfully retrieved and displayed."); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("3. Get statistics for the selected metric over the last day."); logger.info(""" Statistics refer to the various mathematical calculations that can be performed on the collected metrics to derive meaningful insights. Statistics provide a way to summarize and analyze the data collected for a specific metric over a specified time period. """); waitForInputToContinue(scanner); String metricOption = ""; ArrayList<String> statTypes = new ArrayList<>(); statTypes.add("SampleCount"); Learn the basics 2888 Amazon CloudWatch User Guide statTypes.add("Average"); statTypes.add("Sum"); statTypes.add("Minimum"); statTypes.add("Maximum"); for (int t = 0; t < 5; t++) { logger.info(" " + (t + 1) + ". {}", statTypes.get(t)); } logger.info("Select a metric statistic by entering a number from the preceding list:"); num = Integer.parseInt(scanner.nextLine()); if (1 <= num && num <= 5) { metricOption = statTypes.get(num - 1); } else { logger.info("You did not select a valid option."); return; } logger.info("You selected " + metricOption); waitForInputToContinue(scanner); try { CompletableFuture<GetMetricStatisticsResponse> future = cwActions.getAndDisplayMetricStatisticsAsync(selectedNamespace, selectedMetrics, metricOption, myDate, myDimension); future.join(); logger.info("Metric statistics retrieved successfully."); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("4. Get CloudWatch estimated billing for the last week."); waitForInputToContinue(scanner); try { Learn the basics 2889 Amazon CloudWatch User Guide CompletableFuture<GetMetricStatisticsResponse> future = cwActions.getMetricStatisticsAsync(costDateWeek); future.join(); logger.info("Metric statistics successfully retrieved and displayed."); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("5. Create a new CloudWatch dashboard with metrics."); waitForInputToContinue(scanner); try { CompletableFuture<PutDashboardResponse> future = cwActions.createDashboardWithMetricsAsync(dashboardName, dashboardJson); future.join(); } catch (RuntimeException | IOException rt) { Throwable cause = rt.getCause(); if (cause instanceof DashboardInvalidInputErrorException cwEx) { logger.info("Invalid CloudWatch data. Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("6. List dashboards using a paginator."); waitForInputToContinue(scanner); try { Learn the basics 2890 Amazon CloudWatch User Guide CompletableFuture<Void>
acw-ug-823
acw-ug.pdf
823
Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("5. Create a new CloudWatch dashboard with metrics."); waitForInputToContinue(scanner); try { CompletableFuture<PutDashboardResponse> future = cwActions.createDashboardWithMetricsAsync(dashboardName, dashboardJson); future.join(); } catch (RuntimeException | IOException rt) { Throwable cause = rt.getCause(); if (cause instanceof DashboardInvalidInputErrorException cwEx) { logger.info("Invalid CloudWatch data. Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("6. List dashboards using a paginator."); waitForInputToContinue(scanner); try { Learn the basics 2890 Amazon CloudWatch User Guide CompletableFuture<Void> future = cwActions.listDashboardsAsync(); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("7. Create a new custom metric by adding data to it."); logger.info(""" The primary benefit of using a custom metric in Amazon CloudWatch is the ability to monitor and collect data that is specific to your application or infrastructure. """); waitForInputToContinue(scanner); try { CompletableFuture<PutMetricDataResponse> future = cwActions.createNewCustomMetricAsync(dataPoint); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); Learn the basics 2891 Amazon CloudWatch User Guide logger.info("8. Add an additional metric to the dashboard."); waitForInputToContinue(scanner); try { CompletableFuture<PutDashboardResponse> future = cwActions.addMetricToDashboardAsync(dashboardAdd, dashboardName); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof DashboardInvalidInputErrorException cwEx) { logger.info("Invalid CloudWatch data. Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } logger.info(DASHES); logger.info(DASHES); logger.info("9. Create an alarm for the custom metric."); waitForInputToContinue(scanner); String alarmName = "" ; try { CompletableFuture<String> future = cwActions.createAlarmAsync(settings); alarmName = future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof LimitExceededException cwEx) { logger.info("The quota for alarms has been reached: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("10. Describe ten current alarms."); Learn the basics 2892 Amazon CloudWatch User Guide waitForInputToContinue(scanner); try { CompletableFuture<Void> future = cwActions.describeAlarmsAsync(); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("11. Get current data for new custom metric."); try { CompletableFuture<Void> future = cwActions.getCustomMetricDataAsync(settings); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("12. Push data into the custom metric to trigger the alarm."); waitForInputToContinue(scanner); try { Learn the basics 2893 Amazon CloudWatch User Guide CompletableFuture<PutMetricDataResponse> future = cwActions.addMetricDataForAlarmAsync(settings); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("13. Check the alarm state using the action DescribeAlarmsForMetric."); waitForInputToContinue(scanner); try { CompletableFuture<Void> future = cwActions.checkForMetricAlarmAsync(settings); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("14. Get alarm history for the new alarm."); waitForInputToContinue(scanner); try { Learn the basics 2894 Amazon CloudWatch User Guide CompletableFuture<Void> future = cwActions.getAlarmHistoryAsync(settings, myDate); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } logger.info(DASHES); logger.info(DASHES); logger.info("15. Add an anomaly detector for the custom metric."); logger.info(""" An anomaly detector is a feature that automatically detects unusual patterns or deviations in your monitored metrics. It uses machine learning algorithms to analyze the historical behavior of your metrics and establish a baseline. The anomaly detector then compares the current metric values against this baseline and identifies any anomalies or outliers that may indicate potential issues or unexpected changes in your system's performance or behavior. """); waitForInputToContinue(scanner); try { CompletableFuture<Void> future = cwActions.addAnomalyDetectorAsync(settings); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { Learn
acw-ug-824
acw-ug.pdf
824
feature that automatically detects unusual patterns or deviations in your monitored metrics. It uses machine learning algorithms to analyze the historical behavior of your metrics and establish a baseline. The anomaly detector then compares the current metric values against this baseline and identifies any anomalies or outliers that may indicate potential issues or unexpected changes in your system's performance or behavior. """); waitForInputToContinue(scanner); try { CompletableFuture<Void> future = cwActions.addAnomalyDetectorAsync(settings); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { Learn the basics 2895 Amazon CloudWatch User Guide logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("16. Describe current anomaly detectors."); waitForInputToContinue(scanner); try { CompletableFuture<Void> future = cwActions.describeAnomalyDetectorsAsync(settings); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("17. Get a metric image for the custom metric."); try { CompletableFuture<Void> future = cwActions.downloadAndSaveMetricImageAsync(metricImage); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; Learn the basics 2896 Amazon CloudWatch User Guide } logger.info(DASHES); logger.info(DASHES); logger.info("18. Clean up the Amazon CloudWatch resources."); try { logger.info(". Delete the Dashboard."); waitForInputToContinue(scanner); CompletableFuture<DeleteDashboardsResponse> future = cwActions.deleteDashboardAsync(dashboardName); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } try { logger.info("Delete the alarm."); waitForInputToContinue(scanner); CompletableFuture<DeleteAlarmsResponse> future = cwActions.deleteCWAlarmAsync(alarmName); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } try { logger.info("Delete the anomaly detector."); Learn the basics 2897 Amazon CloudWatch User Guide waitForInputToContinue(scanner); CompletableFuture<DeleteAnomalyDetectorResponse> future = cwActions.deleteAnomalyDetectorAsync(settings); future.join(); } catch (RuntimeException rt) { Throwable cause = rt.getCause(); if (cause instanceof CloudWatchException cwEx) { logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode()); } else { logger.info("An unexpected error occurred: {}", rt.getMessage()); } throw cause; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("The Amazon CloudWatch example scenario is complete."); logger.info(DASHES); } private static void waitForInputToContinue(Scanner scanner) { while (true) { logger.info(""); logger.info("Enter 'c' followed by <ENTER> to continue:"); String input = scanner.nextLine(); if (input.trim().equalsIgnoreCase("c")) { logger.info("Continuing with the program..."); logger.info(""); break; } else { // Handle invalid input. logger.info("Invalid input. Please try again."); } } } } A wrapper class for CloudWatch SDK methods. Learn the basics 2898 Amazon CloudWatch User Guide public class CloudWatchActions { private static CloudWatchAsyncClient cloudWatchAsyncClient; private static final Logger logger = LoggerFactory.getLogger(CloudWatchActions.class); /** * Retrieves an asynchronous CloudWatch client instance. * * <p> * This method ensures that the CloudWatch client is initialized with the following configurations: * <ul> * <li>Maximum concurrency: 100</li> * <li>Connection timeout: 60 seconds</li> * <li>Read timeout: 60 seconds</li> * <li>Write timeout: 60 seconds</li> * <li>API call timeout: 2 minutes</li> * <li>API call attempt timeout: 90 seconds</li> * <li>Retry strategy: STANDARD</li> * </ul> * </p> * * @return the asynchronous CloudWatch client instance */ private static CloudWatchAsyncClient getAsyncClient() { if (cloudWatchAsyncClient == null) { SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder() .maxConcurrency(100) .connectionTimeout(Duration.ofSeconds(60)) .readTimeout(Duration.ofSeconds(60)) .writeTimeout(Duration.ofSeconds(60)) .build(); ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .apiCallTimeout(Duration.ofMinutes(2)) .apiCallAttemptTimeout(Duration.ofSeconds(90)) .retryStrategy(RetryMode.STANDARD) .build(); cloudWatchAsyncClient = CloudWatchAsyncClient.builder() Learn the basics 2899 Amazon CloudWatch User Guide .httpClient(httpClient) .overrideConfiguration(overrideConfig) .build(); } return cloudWatchAsyncClient; } /** * Deletes an Anomaly Detector. * * @param fileName the name of the file containing the Anomaly Detector configuration * @return a CompletableFuture that represents the asynchronous deletion of the Anomaly Detector */ public CompletableFuture<DeleteAnomalyDetectorResponse> deleteAnomalyDetectorAsync(String fileName) { CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); return new ObjectMapper().readTree(parser); // Return the root node } catch (IOException e) { throw new RuntimeException("Failed to read or parse the file", e); } }); return readFileFuture.thenCompose(rootNode -> { String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder() .metricName(customMetricName) .namespace(customMetricNamespace) .stat("Maximum") .build(); Learn the basics 2900 Amazon CloudWatch User Guide DeleteAnomalyDetectorRequest request = DeleteAnomalyDetectorRequest.builder() .singleMetricAnomalyDetector(singleMetricAnomalyDetector) .build(); return getAsyncClient().deleteAnomalyDetector(request); }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Failed to delete the Anomaly Detector", exception); } else { logger.info("Successfully deleted the Anomaly Detector."); } }); } /** * Deletes a CloudWatch alarm. * * @param alarmName the name of the alarm to be deleted * @return a {@link CompletableFuture} representing the asynchronous operation to delete the alarm * the {@link DeleteAlarmsResponse} is returned when the operation completes
acw-ug-825
acw-ug.pdf
825
= rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder() .metricName(customMetricName) .namespace(customMetricNamespace) .stat("Maximum") .build(); Learn the basics 2900 Amazon CloudWatch User Guide DeleteAnomalyDetectorRequest request = DeleteAnomalyDetectorRequest.builder() .singleMetricAnomalyDetector(singleMetricAnomalyDetector) .build(); return getAsyncClient().deleteAnomalyDetector(request); }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Failed to delete the Anomaly Detector", exception); } else { logger.info("Successfully deleted the Anomaly Detector."); } }); } /** * Deletes a CloudWatch alarm. * * @param alarmName the name of the alarm to be deleted * @return a {@link CompletableFuture} representing the asynchronous operation to delete the alarm * the {@link DeleteAlarmsResponse} is returned when the operation completes successfully, * or a {@link RuntimeException} is thrown if the operation fails */ public CompletableFuture<DeleteAlarmsResponse> deleteCWAlarmAsync(String alarmName) { DeleteAlarmsRequest request = DeleteAlarmsRequest.builder() .alarmNames(alarmName) .build(); return getAsyncClient().deleteAlarms(request) .whenComplete((response, exception) -> { if (exception != null) { throw new RuntimeException("Failed to delete the alarm:{} " + alarmName, exception); } else { logger.info("Successfully deleted alarm {} ", alarmName); } }); } /** Learn the basics 2901 Amazon CloudWatch User Guide * Deletes the specified dashboard. * * @param dashboardName the name of the dashboard to be deleted * @return a {@link CompletableFuture} representing the asynchronous operation of deleting the dashboard * @throws RuntimeException if the dashboard deletion fails */ public CompletableFuture<DeleteDashboardsResponse> deleteDashboardAsync(String dashboardName) { DeleteDashboardsRequest dashboardsRequest = DeleteDashboardsRequest.builder() .dashboardNames(dashboardName) .build(); return getAsyncClient().deleteDashboards(dashboardsRequest) .whenComplete((response, exception) -> { if (exception != null) { throw new RuntimeException("Failed to delete the dashboard: " + dashboardName, exception); } else { logger.info("{} was successfully deleted.", dashboardName); } }); } /** * Retrieves and saves a custom metric image to a file. * * @param fileName the name of the file to save the metric image to * @return a {@link CompletableFuture} that completes when the image has been saved to the file */ public CompletableFuture<Void> downloadAndSaveMetricImageAsync(String fileName) { logger.info("Getting Image data for custom metric."); String myJSON = """ { "title": "Example Metric Graph", "view": "timeSeries", "stacked ": false, "period": 10, "width": 1400, "height": 600, Learn the basics 2902 Amazon CloudWatch User Guide "metrics": [ [ "AWS/Billing", "EstimatedCharges", "Currency", "USD" ] ] } """; GetMetricWidgetImageRequest imageRequest = GetMetricWidgetImageRequest.builder() .metricWidget(myJSON) .build(); return getAsyncClient().getMetricWidgetImage(imageRequest) .thenCompose(response -> { SdkBytes sdkBytes = response.metricWidgetImage(); byte[] bytes = sdkBytes.asByteArray(); return CompletableFuture.runAsync(() -> { try { File outputFile = new File(fileName); try (FileOutputStream outputStream = new FileOutputStream(outputFile)) { outputStream.write(bytes); } } catch (IOException e) { throw new RuntimeException("Failed to write image to file", e); } }); }) .whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error getting and saving metric image", exception); } else { logger.info("Image data saved successfully to {}", fileName); } }); } Learn the basics 2903 Amazon CloudWatch /** User Guide * Describes the anomaly detectors based on the specified JSON file. * * @param fileName the name of the JSON file containing the custom metric namespace and name * @return a {@link CompletableFuture} that completes when the anomaly detectors have been described * @throws RuntimeException if there is a failure during the operation, such as when reading or parsing the JSON file, * or when describing the anomaly detectors */ public CompletableFuture<Void> describeAnomalyDetectorsAsync(String fileName) { CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); return new ObjectMapper().readTree(parser); } catch (IOException e) { throw new RuntimeException("Failed to read or parse the file", e); } }); return readFileFuture.thenCompose(rootNode -> { try { String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); DescribeAnomalyDetectorsRequest detectorsRequest = DescribeAnomalyDetectorsRequest.builder() .maxResults(10) .metricName(customMetricName) .namespace(customMetricNamespace) .build(); return getAsyncClient().describeAnomalyDetectors(detectorsRequest).thenAccept(response -> { List<AnomalyDetector> anomalyDetectorList = response.anomalyDetectors(); Learn the basics 2904 Amazon CloudWatch User Guide for (AnomalyDetector detector : anomalyDetectorList) { logger.info("Metric name: {} ", detector.singleMetricAnomalyDetector().metricName()); logger.info("State: {} ", detector.stateValue()); } }); } catch (RuntimeException e) { throw new RuntimeException("Failed to describe anomaly detectors", e); } }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error describing anomaly detectors", exception); } }); } /** * Adds an anomaly detector for the given file. * * @param fileName the name of the file containing the anomaly detector configuration * @return a {@link CompletableFuture} that completes when the anomaly detector has been added */ public CompletableFuture<Void> addAnomalyDetectorAsync(String fileName) { CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); return new ObjectMapper().readTree(parser); // Return the root node } catch (IOException e) { throw new RuntimeException("Failed to read or parse the file", e); } }); return readFileFuture.thenCompose(rootNode -> { try { Learn the basics 2905 Amazon CloudWatch User Guide String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder() .metricName(customMetricName) .namespace(customMetricNamespace) .stat("Maximum") .build(); PutAnomalyDetectorRequest anomalyDetectorRequest = PutAnomalyDetectorRequest.builder() .singleMetricAnomalyDetector(singleMetricAnomalyDetector) .build(); return getAsyncClient().putAnomalyDetector(anomalyDetectorRequest).thenAccept(response -> { logger.info("Added anomaly detector for metric {}", customMetricName); }); } catch (Exception e) { throw new RuntimeException("Failed to create anomaly detector", e); } }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error adding anomaly detector", exception); } });
acw-ug-826
acw-ug.pdf
826
the root node } catch (IOException e) { throw new RuntimeException("Failed to read or parse the file", e); } }); return readFileFuture.thenCompose(rootNode -> { try { Learn the basics 2905 Amazon CloudWatch User Guide String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder() .metricName(customMetricName) .namespace(customMetricNamespace) .stat("Maximum") .build(); PutAnomalyDetectorRequest anomalyDetectorRequest = PutAnomalyDetectorRequest.builder() .singleMetricAnomalyDetector(singleMetricAnomalyDetector) .build(); return getAsyncClient().putAnomalyDetector(anomalyDetectorRequest).thenAccept(response -> { logger.info("Added anomaly detector for metric {}", customMetricName); }); } catch (Exception e) { throw new RuntimeException("Failed to create anomaly detector", e); } }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error adding anomaly detector", exception); } }); } /** * Retrieves the alarm history for a given alarm name and date range. * * @param fileName the path to the JSON file containing the alarm name * @param date the date to start the alarm history search (in the format "yyyy-MM-dd'T'HH:mm:ss'Z'") * @return a {@code CompletableFuture<Void>} that completes when the alarm history has been retrieved and processed Learn the basics 2906 Amazon CloudWatch */ User Guide public CompletableFuture<Void> getAlarmHistoryAsync(String fileName, String date) { CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); return rootNode.findValue("exampleAlarmName").asText(); // Return alarmName from the JSON file } catch (IOException e) { throw new RuntimeException("Failed to read or parse the file", e); } }); // Use the alarm name to describe alarm history with a paginator. return readFileFuture.thenCompose(alarmName -> { try { Instant start = Instant.parse(date); Instant endDate = Instant.now(); DescribeAlarmHistoryRequest historyRequest = DescribeAlarmHistoryRequest.builder() .startDate(start) .endDate(endDate) .alarmName(alarmName) .historyItemType(HistoryItemType.ACTION) .build(); // Use the paginator to paginate through alarm history pages. DescribeAlarmHistoryPublisher historyPublisher = getAsyncClient().describeAlarmHistoryPaginator(historyRequest); CompletableFuture<Void> future = historyPublisher .subscribe(response -> response.alarmHistoryItems().forEach(item -> { logger.info("History summary: {}", item.historySummary()); logger.info("Timestamp: {}", item.timestamp()); })) .whenComplete((result, exception) -> { if (exception != null) { Learn the basics 2907 Amazon CloudWatch User Guide logger.error("Error occurred while getting alarm history: " + exception.getMessage(), exception); } else { logger.info("Successfully retrieved all alarm history."); } }); // Return the future to the calling code for further handling return future; } catch (Exception e) { throw new RuntimeException("Failed to process alarm history", e); } }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error completing alarm history processing", exception); } }); } /** * Checks for a metric alarm in AWS CloudWatch. * * @param fileName the name of the file containing the JSON configuration for the custom metric * @return a {@link CompletableFuture} that completes when the check for the metric alarm is complete */ public CompletableFuture<Void> checkForMetricAlarmAsync(String fileName) { CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); return rootNode.toString(); // Return JSON as a string for further processing } catch (IOException e) { throw new RuntimeException("Failed to read file", e); } Learn the basics 2908 Amazon CloudWatch }); User Guide return readFileFuture.thenCompose(jsonContent -> { try { com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent); String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); DescribeAlarmsForMetricRequest metricRequest = DescribeAlarmsForMetricRequest.builder() .metricName(customMetricName) .namespace(customMetricNamespace) .build(); return checkForAlarmAsync(metricRequest, customMetricName, 10); } catch (IOException e) { throw new RuntimeException("Failed to parse JSON content", e); } }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error checking metric alarm", exception); } }); } // Recursive method to check for the alarm. /** * Checks for the existence of an alarm asynchronously for the specified metric. * * @param metricRequest the request to describe the alarms for the specified metric * @param customMetricName the name of the custom metric to check for an alarm * @param retries the number of retries to perform if no alarm is found * @return a {@link CompletableFuture} that completes when an alarm is found or the maximum number of retries has been reached Learn the basics 2909 Amazon CloudWatch */ User Guide private static CompletableFuture<Void> checkForAlarmAsync(DescribeAlarmsForMetricRequest metricRequest, String customMetricName, int retries) { if (retries == 0) { return CompletableFuture.completedFuture(null).thenRun(() -> logger.info("No Alarm state found for {} after 10 retries.", customMetricName) ); } return (getAsyncClient().describeAlarmsForMetric(metricRequest).thenCompose(response -> { if (response.hasMetricAlarms()) { logger.info("Alarm state found for {}", customMetricName); return CompletableFuture.completedFuture(null); // Alarm found, complete the future } else { return CompletableFuture.runAsync(() -> { try { Thread.sleep(20000); logger.info("."); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while waiting to retry", e); } }).thenCompose(v -> checkForAlarmAsync(metricRequest, customMetricName, retries - 1)); // Recursive call } })); } /** * Adds metric data for an alarm asynchronously. * * @param fileName the name of the JSON file containing the metric data * @return a CompletableFuture that asynchronously returns the PutMetricDataResponse */ public CompletableFuture<PutMetricDataResponse> addMetricDataForAlarmAsync(String fileName) { Learn the basics 2910 Amazon CloudWatch User Guide CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); return rootNode.toString(); // Return JSON as a string for further processing } catch (IOException e) { throw
acw-ug-827
acw-ug.pdf
827
waiting to retry", e); } }).thenCompose(v -> checkForAlarmAsync(metricRequest, customMetricName, retries - 1)); // Recursive call } })); } /** * Adds metric data for an alarm asynchronously. * * @param fileName the name of the JSON file containing the metric data * @return a CompletableFuture that asynchronously returns the PutMetricDataResponse */ public CompletableFuture<PutMetricDataResponse> addMetricDataForAlarmAsync(String fileName) { Learn the basics 2910 Amazon CloudWatch User Guide CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); return rootNode.toString(); // Return JSON as a string for further processing } catch (IOException e) { throw new RuntimeException("Failed to read file", e); } }); return readFileFuture.thenCompose(jsonContent -> { try { com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent); String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); Instant instant = Instant.now(); // Create MetricDatum objects. MetricDatum datum1 = MetricDatum.builder() .metricName(customMetricName) .unit(StandardUnit.NONE) .value(1001.00) .timestamp(instant) .build(); MetricDatum datum2 = MetricDatum.builder() .metricName(customMetricName) .unit(StandardUnit.NONE) .value(1002.00) .timestamp(instant) .build(); List<MetricDatum> metricDataList = new ArrayList<>(); metricDataList.add(datum1); metricDataList.add(datum2); // Build the PutMetricData request. Learn the basics 2911 Amazon CloudWatch User Guide PutMetricDataRequest request = PutMetricDataRequest.builder() .namespace(customMetricNamespace) .metricData(metricDataList) .build(); // Send the request asynchronously. return getAsyncClient().putMetricData(request); } catch (IOException e) { CompletableFuture<PutMetricDataResponse> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(new RuntimeException("Failed to parse JSON content", e)); return failedFuture; } }).whenComplete((response, exception) -> { if (exception != null) { logger.error("Failed to put metric data: " + exception.getMessage(), exception); } else { logger.info("Added metric values for metric."); } }); } /** * Retrieves custom metric data from the AWS CloudWatch service. * * @param fileName the name of the file containing the custom metric information * @return a {@link CompletableFuture} that completes when the metric data has been retrieved */ public CompletableFuture<Void> getCustomMetricDataAsync(String fileName) { CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { try { // Read values from the JSON file. JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); Learn the basics 2912 Amazon CloudWatch User Guide return rootNode.toString(); // Return JSON as a string for further processing } catch (IOException e) { throw new RuntimeException("Failed to read file", e); } }); return readFileFuture.thenCompose(jsonContent -> { try { // Parse the JSON string to extract relevant values. com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent); String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); // Set the current time and date range for metric query. Instant nowDate = Instant.now(); long hours = 1; long minutes = 30; Instant endTime = nowDate.plus(hours, ChronoUnit.HOURS).plus(minutes, ChronoUnit.MINUTES); Metric met = Metric.builder() .metricName(customMetricName) .namespace(customMetricNamespace) .build(); MetricStat metStat = MetricStat.builder() .stat("Maximum") .period(60) // Assuming period in seconds .metric(met) .build(); MetricDataQuery dataQuery = MetricDataQuery.builder() .metricStat(metStat) .id("foo2") .returnData(true) .build(); List<MetricDataQuery> dq = new ArrayList<>(); dq.add(dataQuery); Learn the basics 2913 Amazon CloudWatch User Guide GetMetricDataRequest getMetricDataRequest = GetMetricDataRequest.builder() .maxDatapoints(10) .scanBy(ScanBy.TIMESTAMP_DESCENDING) .startTime(nowDate) .endTime(endTime) .metricDataQueries(dq) .build(); // Call the async method for CloudWatch data retrieval. return getAsyncClient().getMetricData(getMetricDataRequest); } catch (IOException e) { throw new RuntimeException("Failed to parse JSON content", e); } }).thenAccept(response -> { List<MetricDataResult> data = response.metricDataResults(); for (MetricDataResult item : data) { logger.info("The label is: {}", item.label()); logger.info("The status code is: {}", item.statusCode().toString()); } }).exceptionally(exception -> { throw new RuntimeException("Failed to get metric data", exception); }); } /** * Describes the CloudWatch alarms of the 'METRIC_ALARM' type. * * @return a {@link CompletableFuture} that represents the asynchronous operation * of describing the CloudWatch alarms. The future completes when the * operation is finished, either successfully or with an error. */ public CompletableFuture<Void> describeAlarmsAsync() { List<AlarmType> typeList = new ArrayList<>(); typeList.add(AlarmType.METRIC_ALARM); DescribeAlarmsRequest alarmsRequest = DescribeAlarmsRequest.builder() .alarmTypes(typeList) .maxRecords(10) .build(); Learn the basics 2914 Amazon CloudWatch User Guide return getAsyncClient().describeAlarms(alarmsRequest) .thenAccept(response -> { List<MetricAlarm> alarmList = response.metricAlarms(); for (MetricAlarm alarm : alarmList) { logger.info("Alarm name: {}", alarm.alarmName()); logger.info("Alarm description: {} ", alarm.alarmDescription()); } }) .whenComplete((response, ex) -> { if (ex != null) { logger.info("Failed to describe alarms: {}", ex.getMessage()); } else { logger.info("Successfully described alarms."); } }); } /** * Creates an alarm based on the configuration provided in a JSON file. * * @param fileName the name of the JSON file containing the alarm configuration * @return a CompletableFuture that represents the asynchronous operation of creating the alarm * @throws RuntimeException if an exception occurs while reading the JSON file or creating the alarm */ public CompletableFuture<String> createAlarmAsync(String fileName) { com.fasterxml.jackson.databind.JsonNode rootNode; try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); rootNode = new ObjectMapper().readTree(parser); } catch (IOException e) { throw new RuntimeException("Failed to read the alarm configuration file", e); } // Extract values from the JSON node. String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); Learn the basics 2915 Amazon CloudWatch User Guide String customMetricName = rootNode.findValue("customMetricName").asText(); String alarmName = rootNode.findValue("exampleAlarmName").asText(); String emailTopic = rootNode.findValue("emailTopic").asText(); String accountId = rootNode.findValue("accountId").asText(); String region = rootNode.findValue("region").asText(); // Create a List for alarm actions. List<String> alarmActions = new ArrayList<>(); alarmActions.add("arn:aws:sns:" + region + ":" + accountId + ":" + emailTopic); PutMetricAlarmRequest alarmRequest = PutMetricAlarmRequest.builder() .alarmActions(alarmActions) .alarmDescription("Example metric alarm") .alarmName(alarmName) .comparisonOperator(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD) .threshold(100.00) .metricName(customMetricName) .namespace(customMetricNamespace) .evaluationPeriods(1) .period(10)
acw-ug-828
acw-ug.pdf
828
new JsonFactory().createParser(new File(fileName)); rootNode = new ObjectMapper().readTree(parser); } catch (IOException e) { throw new RuntimeException("Failed to read the alarm configuration file", e); } // Extract values from the JSON node. String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); Learn the basics 2915 Amazon CloudWatch User Guide String customMetricName = rootNode.findValue("customMetricName").asText(); String alarmName = rootNode.findValue("exampleAlarmName").asText(); String emailTopic = rootNode.findValue("emailTopic").asText(); String accountId = rootNode.findValue("accountId").asText(); String region = rootNode.findValue("region").asText(); // Create a List for alarm actions. List<String> alarmActions = new ArrayList<>(); alarmActions.add("arn:aws:sns:" + region + ":" + accountId + ":" + emailTopic); PutMetricAlarmRequest alarmRequest = PutMetricAlarmRequest.builder() .alarmActions(alarmActions) .alarmDescription("Example metric alarm") .alarmName(alarmName) .comparisonOperator(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD) .threshold(100.00) .metricName(customMetricName) .namespace(customMetricNamespace) .evaluationPeriods(1) .period(10) .statistic("Maximum") .datapointsToAlarm(1) .treatMissingData("ignore") .build(); // Call the putMetricAlarm asynchronously and handle the result. return getAsyncClient().putMetricAlarm(alarmRequest) .handle((response, ex) -> { if (ex != null) { logger.info("Failed to create alarm: {}", ex.getMessage()); throw new RuntimeException("Failed to create alarm", ex); } else { logger.info("{} was successfully created!", alarmName); return alarmName; } }); } /** * Adds a metric to a dashboard asynchronously. * Learn the basics 2916 Amazon CloudWatch User Guide * @param fileName the name of the file containing the dashboard content * @param dashboardName the name of the dashboard to be updated * @return a {@link CompletableFuture} representing the asynchronous operation, which will complete with a * {@link PutDashboardResponse} when the dashboard is successfully updated */ public CompletableFuture<PutDashboardResponse> addMetricToDashboardAsync(String fileName, String dashboardName) { String dashboardBody; try { dashboardBody = readFileAsString(fileName); } catch (IOException e) { throw new RuntimeException("Failed to read the dashboard file", e); } PutDashboardRequest dashboardRequest = PutDashboardRequest.builder() .dashboardName(dashboardName) .dashboardBody(dashboardBody) .build(); return getAsyncClient().putDashboard(dashboardRequest) .handle((response, ex) -> { if (ex != null) { logger.info("Failed to update dashboard: {}", ex.getMessage()); throw new RuntimeException("Error updating dashboard", ex); } else { logger.info("{} was successfully updated.", dashboardName); return response; } }); } /** * Creates a new custom metric. * * @param dataPoint the data point to be added to the custom metric * @return a {@link CompletableFuture} representing the asynchronous operation of adding the custom metric */ public CompletableFuture<PutMetricDataResponse> createNewCustomMetricAsync(Double dataPoint) { Dimension dimension = Dimension.builder() .name("UNIQUE_PAGES") Learn the basics 2917 Amazon CloudWatch User Guide .value("URLS") .build(); // Set an Instant object for the current time in UTC. String time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT); Instant instant = Instant.parse(time); // Create the MetricDatum. MetricDatum datum = MetricDatum.builder() .metricName("PAGES_VISITED") .unit(StandardUnit.NONE) .value(dataPoint) .timestamp(instant) .dimensions(dimension) .build(); PutMetricDataRequest request = PutMetricDataRequest.builder() .namespace("SITE/TRAFFIC") .metricData(datum) .build(); return getAsyncClient().putMetricData(request) .whenComplete((response, ex) -> { if (ex != null) { throw new RuntimeException("Error adding custom metric", ex); } else { logger.info("Successfully added metric values for PAGES_VISITED."); } }); } /** * Lists the available dashboards. * * @return a {@link CompletableFuture} that completes when the operation is finished. * The future will complete exceptionally if an error occurs while listing the dashboards. */ public CompletableFuture<Void> listDashboardsAsync() { ListDashboardsRequest listDashboardsRequest = ListDashboardsRequest.builder().build(); Learn the basics 2918 Amazon CloudWatch User Guide ListDashboardsPublisher paginator = getAsyncClient().listDashboardsPaginator(listDashboardsRequest); return paginator.subscribe(response -> { response.dashboardEntries().forEach(entry -> { logger.info("Dashboard name is: {} ", entry.dashboardName()); logger.info("Dashboard ARN is: {} ", entry.dashboardArn()); }); }).exceptionally(ex -> { logger.info("Failed to list dashboards: {} ", ex.getMessage()); throw new RuntimeException("Error occurred while listing dashboards", ex); }); } /** * Creates a new dashboard with the specified name and metrics from the given file. * * @param dashboardName the name of the dashboard to be created * @param fileName the name of the file containing the dashboard body * @return a {@link CompletableFuture} representing the asynchronous operation of creating the dashboard * @throws IOException if there is an error reading the dashboard body from the file */ public CompletableFuture<PutDashboardResponse> createDashboardWithMetricsAsync(String dashboardName, String fileName) throws IOException { String dashboardBody = readFileAsString(fileName); PutDashboardRequest dashboardRequest = PutDashboardRequest.builder() .dashboardName(dashboardName) .dashboardBody(dashboardBody) .build(); return getAsyncClient().putDashboard(dashboardRequest) .handle((response, ex) -> { if (ex != null) { logger.info("Failed to create dashboard: {}", ex.getMessage()); throw new RuntimeException("Dashboard creation failed", ex); } else { // Handle the normal response case logger.info("{} was successfully created.", dashboardName); Learn the basics 2919 Amazon CloudWatch User Guide List<DashboardValidationMessage> messages = response.dashboardValidationMessages(); if (messages.isEmpty()) { logger.info("There are no messages in the new Dashboard."); } else { for (DashboardValidationMessage message : messages) { logger.info("Message: {}", message.message()); } } return response; // Return the response for further use } }); } /** * Retrieves the metric statistics for the "EstimatedCharges" metric in the "AWS/Billing" namespace. * * @param costDateWeek the start date for the metric statistics, in the format of an ISO-8601 date string (e.g., "2023-04-05") * @return a {@link CompletableFuture} that, when completed, contains the {@link GetMetricStatisticsResponse} with the retrieved metric statistics * @throws RuntimeException if the metric statistics cannot be retrieved successfully */ public CompletableFuture<GetMetricStatisticsResponse> getMetricStatisticsAsync(String costDateWeek) { Instant start = Instant.parse(costDateWeek); Instant endDate = Instant.now(); // Define dimension Dimension dimension = Dimension.builder() .name("Currency") .value("USD") .build(); List<Dimension> dimensionList = new ArrayList<>(); dimensionList.add(dimension); GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder() .metricName("EstimatedCharges") Learn the basics 2920 Amazon CloudWatch User Guide .namespace("AWS/Billing") .dimensions(dimensionList) .statistics(Statistic.MAXIMUM) .startTime(start) .endTime(endDate) .period(86400) // One day period .build(); return
acw-ug-829
acw-ug.pdf
829
the start date for the metric statistics, in the format of an ISO-8601 date string (e.g., "2023-04-05") * @return a {@link CompletableFuture} that, when completed, contains the {@link GetMetricStatisticsResponse} with the retrieved metric statistics * @throws RuntimeException if the metric statistics cannot be retrieved successfully */ public CompletableFuture<GetMetricStatisticsResponse> getMetricStatisticsAsync(String costDateWeek) { Instant start = Instant.parse(costDateWeek); Instant endDate = Instant.now(); // Define dimension Dimension dimension = Dimension.builder() .name("Currency") .value("USD") .build(); List<Dimension> dimensionList = new ArrayList<>(); dimensionList.add(dimension); GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder() .metricName("EstimatedCharges") Learn the basics 2920 Amazon CloudWatch User Guide .namespace("AWS/Billing") .dimensions(dimensionList) .statistics(Statistic.MAXIMUM) .startTime(start) .endTime(endDate) .period(86400) // One day period .build(); return getAsyncClient().getMetricStatistics(statisticsRequest) .whenComplete((response, exception) -> { if (response != null) { List<Datapoint> data = response.datapoints(); if (!data.isEmpty()) { for (Datapoint datapoint : data) { logger.info("Timestamp: {} Maximum value: {})", datapoint.timestamp(), datapoint.maximum()); } } else { logger.info("The returned data list is empty"); } } else { throw new RuntimeException("Failed to get metric statistics: " + exception.getMessage(), exception); } }); } /** * Retrieves and displays metric statistics for the specified parameters. * * @param nameSpace the namespace for the metric * @param metVal the name of the metric * @param metricOption the statistic to retrieve for the metric (e.g., "Maximum", "Average") * @param date the date for which to retrieve the metric statistics, in the format "yyyy-MM-dd'T'HH:mm:ss'Z'" * @param myDimension the dimension(s) to filter the metric statistics by * @return a {@link CompletableFuture} that completes when the metric statistics have been retrieved and displayed */ public CompletableFuture<GetMetricStatisticsResponse> getAndDisplayMetricStatisticsAsync(String nameSpace, String metVal, Learn the basics 2921 Amazon CloudWatch User Guide String metricOption, String date, Dimension myDimension) { Instant start = Instant.parse(date); Instant endDate = Instant.now(); // Building the request for metric statistics. GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder() .endTime(endDate) .startTime(start) .dimensions(myDimension) .metricName(metVal) .namespace(nameSpace) .period(86400) // 1 day period .statistics(Statistic.fromValue(metricOption)) .build(); return getAsyncClient().getMetricStatistics(statisticsRequest) .whenComplete((response, exception) -> { if (response != null) { List<Datapoint> data = response.datapoints(); if (!data.isEmpty()) { for (Datapoint datapoint : data) { logger.info("Timestamp: {} Maximum value: {}", datapoint.timestamp(), datapoint.maximum()); } } else { logger.info("The returned data list is empty"); } } else { logger.info("Failed to get metric statistics: {} ", exception.getMessage()); } }) .exceptionally(exception -> { throw new RuntimeException("Error while getting metric statistics: " + exception.getMessage(), exception); }); } /** * Retrieves a list of metric names for the specified namespace. Learn the basics 2922 Amazon CloudWatch * User Guide * @param namespace the namespace for which to retrieve the metric names * @return a {@link CompletableFuture} that, when completed, contains an {@link ArrayList} of * the metric names in the specified namespace * @throws RuntimeException if an error occurs while listing the metrics */ public CompletableFuture<ArrayList<String>> listMetsAsync(String namespace) { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .build(); ListMetricsPublisher metricsPaginator = getAsyncClient().listMetricsPaginator(request); Set<String> metSet = new HashSet<>(); CompletableFuture<Void> future = metricsPaginator.subscribe(response -> { response.metrics().forEach(metric -> { String metricName = metric.metricName(); metSet.add(metricName); }); }); return future .thenApply(ignored -> new ArrayList<>(metSet)) .exceptionally(exception -> { throw new RuntimeException("Failed to list metrics: " + exception.getMessage(), exception); }); } /** * Lists the available namespaces for the current AWS account. * * @return a {@link CompletableFuture} that, when completed, contains an {@link ArrayList} of the available namespace names. * @throws RuntimeException if an error occurs while listing the namespaces. */ public CompletableFuture<ArrayList<String>> listNameSpacesAsync() { ArrayList<String> nameSpaceList = new ArrayList<>(); ListMetricsRequest request = ListMetricsRequest.builder().build(); ListMetricsPublisher metricsPaginator = getAsyncClient().listMetricsPaginator(request); CompletableFuture<Void> future = metricsPaginator.subscribe(response -> { Learn the basics 2923 Amazon CloudWatch User Guide response.metrics().forEach(metric -> { String namespace = metric.namespace(); if (!nameSpaceList.contains(namespace)) { nameSpaceList.add(namespace); } }); }); return future .thenApply(ignored -> nameSpaceList) .exceptionally(exception -> { throw new RuntimeException("Failed to list namespaces: " + exception.getMessage(), exception); }); } /** * Retrieves the specific metric asynchronously. * * @param namespace the namespace of the metric to retrieve * @return a CompletableFuture that completes with the first dimension of the first metric found in the specified namespace, * or throws a RuntimeException if an error occurs or no metrics or dimensions are found */ public CompletableFuture<Dimension> getSpecificMetAsync(String namespace) { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .build(); return getAsyncClient().listMetrics(request).handle((response, exception) -> { if (exception != null) { logger.info("Error occurred while listing metrics: {} ", exception.getMessage()); throw new RuntimeException("Failed to retrieve specific metric dimension", exception); } else { List<Metric> myList = response.metrics(); if (!myList.isEmpty()) { Metric metric = myList.get(0); if (!metric.dimensions().isEmpty()) { return metric.dimensions().get(0); // Return the first dimension } Learn the basics 2924 Amazon CloudWatch } User Guide throw new RuntimeException("No metrics or dimensions found"); } }); } public static String readFileAsString(String file) throws IOException { return new String(Files.readAllBytes(Paths.get(file))); } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • DeleteAlarms • DeleteAnomalyDetector • DeleteDashboards • DescribeAlarmHistory • DescribeAlarms • DescribeAlarmsForMetric • DescribeAnomalyDetectors • GetMetricData • GetMetricStatistics • GetMetricWidgetImage • ListMetrics • PutAnomalyDetector • PutDashboard • PutMetricAlarm • PutMetricData Learn the basics 2925 Amazon CloudWatch Kotlin SDK for Kotlin
acw-ug-830
acw-ug.pdf
830
myList.get(0); if (!metric.dimensions().isEmpty()) { return metric.dimensions().get(0); // Return the first dimension } Learn the basics 2924 Amazon CloudWatch } User Guide throw new RuntimeException("No metrics or dimensions found"); } }); } public static String readFileAsString(String file) throws IOException { return new String(Files.readAllBytes(Paths.get(file))); } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • DeleteAlarms • DeleteAnomalyDetector • DeleteDashboards • DescribeAlarmHistory • DescribeAlarms • DescribeAlarmsForMetric • DescribeAnomalyDetectors • GetMetricData • GetMetricStatistics • GetMetricWidgetImage • ListMetrics • PutAnomalyDetector • PutDashboard • PutMetricAlarm • PutMetricData Learn the basics 2925 Amazon CloudWatch Kotlin SDK for Kotlin Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Run an interactive scenario demonstrating CloudWatch features. /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html To enable billing metrics and statistics for this example, make sure billing alerts are enabled for your account: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ monitor_estimated_charges_with_cloudwatch.html#turning_on_billing_metrics This Kotlin code example performs the following tasks: 1. List available namespaces from Amazon CloudWatch. Select a namespace from the list. 2. List available metrics within the selected namespace. 3. Get statistics for the selected metric over the last day. 4. Get CloudWatch estimated billing for the last week. 5. Create a new CloudWatch dashboard with metrics. 6. List dashboards using a paginator. 7. Create a new custom metric by adding data for it. 8. Add the custom metric to the dashboard. 9. Create an alarm for the custom metric. 10. Describe current alarms. 11. Get current data for the new custom metric. 12. Push data into the custom metric to trigger the alarm. 13. Check the alarm state using the action DescribeAlarmsForMetric. 14. Get alarm history for the new alarm. 15. Add an anomaly detector for the custom metric. Learn the basics 2926 Amazon CloudWatch User Guide 16. Describe current anomaly detectors. 17. Get a metric image for the custom metric. 18. Clean up the Amazon CloudWatch resources. */ val DASHES: String? = String(CharArray(80)).replace("\u0000", "-") suspend fun main(args: Array<String>) { val usage = """ Usage: <myDate> <costDateWeek> <dashboardName> <dashboardJson> <dashboardAdd> <settings> <metricImage> Where: myDate - The start date to use to get metric statistics. (For example, 2023-01-11T18:35:24.00Z.) costDateWeek - The start date to use to get AWS Billing and Cost Management statistics. (For example, 2023-01-11T18:35:24.00Z.) dashboardName - The name of the dashboard to create. dashboardJson - The location of a JSON file to use to create a dashboard. (See Readme file.) dashboardAdd - The location of a JSON file to use to update a dashboard. (See Readme file.) settings - The location of a JSON file from which various values are read. (See Readme file.) metricImage - The location of a BMP file that is used to create a graph. """ if (args.size != 7) { println(usage) System.exit(1) } val myDate = args[0] val costDateWeek = args[1] val dashboardName = args[2] val dashboardJson = args[3] val dashboardAdd = args[4] val settings = args[5] var metricImage = args[6] val dataPoint = "10.0".toDouble() val inOb = Scanner(System.`in`) Learn the basics 2927 Amazon CloudWatch println(DASHES) User Guide println("Welcome to the Amazon CloudWatch example scenario.") println(DASHES) println(DASHES) println("1. List at least five available unique namespaces from Amazon CloudWatch. Select a CloudWatch namespace from the list.") val list: ArrayList<String> = listNameSpaces() for (z in 0..4) { println(" ${z + 1}. ${list[z]}") } var selectedNamespace: String var selectedMetrics = "" var num = inOb.nextLine().toInt() println("You selected $num") if (1 <= num && num <= 5) { selectedNamespace = list[num - 1] } else { println("You did not select a valid option.") exitProcess(1) } println("You selected $selectedNamespace") println(DASHES) println(DASHES) println("2. List available metrics within the selected namespace and select one from the list.") val metList = listMets(selectedNamespace) for (z in 0..4) { println(" ${ z + 1}. ${metList?.get(z)}") } num = inOb.nextLine().toInt() if (1 <= num && num <= 5) { selectedMetrics = metList!![num - 1] } else { println("You did not select a valid option.") System.exit(1) } println("You selected $selectedMetrics") val myDimension = getSpecificMet(selectedNamespace) if (myDimension == null) { println("Error - Dimension is null") Learn the basics 2928 Amazon CloudWatch User Guide exitProcess(1) } println(DASHES) println(DASHES) println("3. Get statistics for the selected metric over the last day.") val metricOption: String val statTypes = ArrayList<String>() statTypes.add("SampleCount") statTypes.add("Average") statTypes.add("Sum") statTypes.add("Minimum") statTypes.add("Maximum") for (t in 0..4) { println(" ${t + 1}. ${statTypes[t]}") } println("Select a metric statistic by entering a number from the preceding list:") num = inOb.nextLine().toInt() if (1 <= num && num <= 5) { metricOption = statTypes[num - 1] } else { println("You did not select a valid option.") exitProcess(1) } println("You selected $metricOption") getAndDisplayMetricStatistics(selectedNamespace, selectedMetrics, metricOption, myDate, myDimension) println(DASHES) println(DASHES) println("4. Get CloudWatch estimated billing for the last
acw-ug-831
acw-ug.pdf
831
CloudWatch User Guide exitProcess(1) } println(DASHES) println(DASHES) println("3. Get statistics for the selected metric over the last day.") val metricOption: String val statTypes = ArrayList<String>() statTypes.add("SampleCount") statTypes.add("Average") statTypes.add("Sum") statTypes.add("Minimum") statTypes.add("Maximum") for (t in 0..4) { println(" ${t + 1}. ${statTypes[t]}") } println("Select a metric statistic by entering a number from the preceding list:") num = inOb.nextLine().toInt() if (1 <= num && num <= 5) { metricOption = statTypes[num - 1] } else { println("You did not select a valid option.") exitProcess(1) } println("You selected $metricOption") getAndDisplayMetricStatistics(selectedNamespace, selectedMetrics, metricOption, myDate, myDimension) println(DASHES) println(DASHES) println("4. Get CloudWatch estimated billing for the last week.") getMetricStatistics(costDateWeek) println(DASHES) println(DASHES) println("5. Create a new CloudWatch dashboard with metrics.") createDashboardWithMetrics(dashboardName, dashboardJson) println(DASHES) println(DASHES) println("6. List dashboards using a paginator.") listDashboards() Learn the basics 2929 Amazon CloudWatch User Guide println(DASHES) println(DASHES) println("7. Create a new custom metric by adding data to it.") createNewCustomMetric(dataPoint) println(DASHES) println(DASHES) println("8. Add an additional metric to the dashboard.") addMetricToDashboard(dashboardAdd, dashboardName) println(DASHES) println(DASHES) println("9. Create an alarm for the custom metric.") val alarmName: String = createAlarm(settings) println(DASHES) println(DASHES) println("10. Describe 10 current alarms.") describeAlarms() println(DASHES) println(DASHES) println("11. Get current data for the new custom metric.") getCustomMetricData(settings) println(DASHES) println(DASHES) println("12. Push data into the custom metric to trigger the alarm.") addMetricDataForAlarm(settings) println(DASHES) println(DASHES) println("13. Check the alarm state using the action DescribeAlarmsForMetric.") checkForMetricAlarm(settings) println(DASHES) println(DASHES) println("14. Get alarm history for the new alarm.") getAlarmHistory(settings, myDate) println(DASHES) println(DASHES) Learn the basics 2930 Amazon CloudWatch User Guide println("15. Add an anomaly detector for the custom metric.") addAnomalyDetector(settings) println(DASHES) println(DASHES) println("16. Describe current anomaly detectors.") describeAnomalyDetectors(settings) println(DASHES) println(DASHES) println("17. Get a metric image for the custom metric.") getAndOpenMetricImage(metricImage) println(DASHES) println(DASHES) println("18. Clean up the Amazon CloudWatch resources.") deleteDashboard(dashboardName) deleteAlarm(alarmName) deleteAnomalyDetector(settings) println(DASHES) println(DASHES) println("The Amazon CloudWatch example scenario is complete.") println(DASHES) } suspend fun deleteAnomalyDetector(fileName: String) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() val singleMetricAnomalyDetectorVal = SingleMetricAnomalyDetector { metricName = customMetricName namespace = customMetricNamespace stat = "Maximum" } val request = DeleteAnomalyDetectorRequest { singleMetricAnomalyDetector = singleMetricAnomalyDetectorVal Learn the basics 2931 Amazon CloudWatch } User Guide CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.deleteAnomalyDetector(request) println("Successfully deleted the Anomaly Detector.") } } suspend fun deleteAlarm(alarmNameVal: String) { val request = DeleteAlarmsRequest { alarmNames = listOf(alarmNameVal) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.deleteAlarms(request) println("Successfully deleted alarm $alarmNameVal") } } suspend fun deleteDashboard(dashboardName: String) { val dashboardsRequest = DeleteDashboardsRequest { dashboardNames = listOf(dashboardName) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.deleteDashboards(dashboardsRequest) println("$dashboardName was successfully deleted.") } } suspend fun getAndOpenMetricImage(fileName: String) { println("Getting Image data for custom metric.") val myJSON = """{ "title": "Example Metric Graph", "view": "timeSeries", "stacked ": false, "period": 10, "width": 1400, "height": 600, "metrics": [ [ "AWS/Billing", "EstimatedCharges", Learn the basics 2932 Amazon CloudWatch User Guide "Currency", "USD" ] ] }""" val imageRequest = GetMetricWidgetImageRequest { metricWidget = myJSON } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricWidgetImage(imageRequest) val bytes = response.metricWidgetImage if (bytes != null) { File(fileName).writeBytes(bytes) } } println("You have successfully written data to $fileName") } suspend fun describeAnomalyDetectors(fileName: String) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() val detectorsRequest = DescribeAnomalyDetectorsRequest { maxResults = 10 metricName = customMetricName namespace = customMetricNamespace } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.describeAnomalyDetectors(detectorsRequest) response.anomalyDetectors?.forEach { detector -> println("Metric name: ${detector.singleMetricAnomalyDetector?.metricName}") println("State: ${detector.stateValue}") } } } Learn the basics 2933 Amazon CloudWatch User Guide suspend fun addAnomalyDetector(fileName: String?) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() val singleMetricAnomalyDetectorVal = SingleMetricAnomalyDetector { metricName = customMetricName namespace = customMetricNamespace stat = "Maximum" } val anomalyDetectorRequest = PutAnomalyDetectorRequest { singleMetricAnomalyDetector = singleMetricAnomalyDetectorVal } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putAnomalyDetector(anomalyDetectorRequest) println("Added anomaly detector for metric $customMetricName.") } } suspend fun getAlarmHistory( fileName: String, date: String, ) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val alarmNameVal = rootNode.findValue("exampleAlarmName").asText() val start = Instant.parse(date) val endDateVal = Instant.now() val historyRequest = DescribeAlarmHistoryRequest { startDate = aws.smithy.kotlin.runtime.time .Instant(start) endDate = Learn the basics 2934 Amazon CloudWatch User Guide aws.smithy.kotlin.runtime.time .Instant(endDateVal) alarmName = alarmNameVal historyItemType = HistoryItemType.Action } CloudWatchClient { credentialsProvider = EnvironmentCredentialsProvider() region = "us-east-1" }.use { cwClient -> val response = cwClient.describeAlarmHistory(historyRequest) val historyItems = response.alarmHistoryItems if (historyItems != null) { if (historyItems.isEmpty()) { println("No alarm history data found for $alarmNameVal.") } else { for (item in historyItems) { println("History summary ${item.historySummary}") println("Time stamp: ${item.timestamp}") } } } } } suspend fun checkForMetricAlarm(fileName: String?) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName))
acw-ug-832
acw-ug.pdf
832
= Instant.now() val historyRequest = DescribeAlarmHistoryRequest { startDate = aws.smithy.kotlin.runtime.time .Instant(start) endDate = Learn the basics 2934 Amazon CloudWatch User Guide aws.smithy.kotlin.runtime.time .Instant(endDateVal) alarmName = alarmNameVal historyItemType = HistoryItemType.Action } CloudWatchClient { credentialsProvider = EnvironmentCredentialsProvider() region = "us-east-1" }.use { cwClient -> val response = cwClient.describeAlarmHistory(historyRequest) val historyItems = response.alarmHistoryItems if (historyItems != null) { if (historyItems.isEmpty()) { println("No alarm history data found for $alarmNameVal.") } else { for (item in historyItems) { println("History summary ${item.historySummary}") println("Time stamp: ${item.timestamp}") } } } } } suspend fun checkForMetricAlarm(fileName: String?) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() var hasAlarm = false var retries = 10 val metricRequest = DescribeAlarmsForMetricRequest { metricName = customMetricName namespace = customMetricNamespace } CloudWatchClient { region = "us-east-1" }.use { cwClient -> while (!hasAlarm && retries > 0) { val response = cwClient.describeAlarmsForMetric(metricRequest) if (response.metricAlarms?.count()!! > 0) { Learn the basics 2935 Amazon CloudWatch User Guide hasAlarm = true } retries-- delay(20000) println(".") } if (!hasAlarm) { println("No Alarm state found for $customMetricName after 10 retries.") } else { println("Alarm state found for $customMetricName.") } } } suspend fun addMetricDataForAlarm(fileName: String?) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() // Set an Instant object. val time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT) val instant = Instant.parse(time) val datum = MetricDatum { metricName = customMetricName unit = StandardUnit.None value = 1001.00 timestamp = aws.smithy.kotlin.runtime.time .Instant(instant) } val datum2 = MetricDatum { metricName = customMetricName unit = StandardUnit.None value = 1002.00 timestamp = aws.smithy.kotlin.runtime.time Learn the basics 2936 Amazon CloudWatch User Guide .Instant(instant) } val metricDataList = ArrayList<MetricDatum>() metricDataList.add(datum) metricDataList.add(datum2) val request = PutMetricDataRequest { namespace = customMetricNamespace metricData = metricDataList } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putMetricData(request) println("Added metric values for for metric $customMetricName") } } suspend fun getCustomMetricData(fileName: String) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() // Set the date. val nowDate = Instant.now() val hours: Long = 1 val minutes: Long = 30 val date2 = nowDate.plus(hours, ChronoUnit.HOURS).plus( minutes, ChronoUnit.MINUTES, ) val met = Metric { metricName = customMetricName namespace = customMetricNamespace } val metStat = Learn the basics 2937 Amazon CloudWatch User Guide MetricStat { stat = "Maximum" period = 1 metric = met } val dataQUery = MetricDataQuery { metricStat = metStat id = "foo2" returnData = true } val dq = ArrayList<MetricDataQuery>() dq.add(dataQUery) val getMetReq = GetMetricDataRequest { maxDatapoints = 10 scanBy = ScanBy.TimestampDescending startTime = aws.smithy.kotlin.runtime.time .Instant(nowDate) endTime = aws.smithy.kotlin.runtime.time .Instant(date2) metricDataQueries = dq } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricData(getMetReq) response.metricDataResults?.forEach { item -> println("The label is ${item.label}") println("The status code is ${item.statusCode}") } } } suspend fun describeAlarms() { val typeList = ArrayList<AlarmType>() typeList.add(AlarmType.MetricAlarm) val alarmsRequest = DescribeAlarmsRequest { alarmTypes = typeList maxRecords = 10 Learn the basics 2938 Amazon CloudWatch } User Guide CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.describeAlarms(alarmsRequest) response.metricAlarms?.forEach { alarm -> println("Alarm name: ${alarm.alarmName}") println("Alarm description: ${alarm.alarmDescription}") } } } suspend fun createAlarm(fileName: String): String { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode: JsonNode = ObjectMapper().readTree(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() val alarmNameVal = rootNode.findValue("exampleAlarmName").asText() val emailTopic = rootNode.findValue("emailTopic").asText() val accountId = rootNode.findValue("accountId").asText() val region2 = rootNode.findValue("region").asText() // Create a List for alarm actions. val alarmActionObs: MutableList<String> = ArrayList() alarmActionObs.add("arn:aws:sns:$region2:$accountId:$emailTopic") val alarmRequest = PutMetricAlarmRequest { alarmActions = alarmActionObs alarmDescription = "Example metric alarm" alarmName = alarmNameVal comparisonOperator = ComparisonOperator.GreaterThanOrEqualToThreshold threshold = 100.00 metricName = customMetricName namespace = customMetricNamespace evaluationPeriods = 1 period = 10 statistic = Statistic.Maximum datapointsToAlarm = 1 treatMissingData = "ignore" } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putMetricAlarm(alarmRequest) Learn the basics 2939 Amazon CloudWatch User Guide println("$alarmNameVal was successfully created!") return alarmNameVal } } suspend fun addMetricToDashboard( fileNameVal: String, dashboardNameVal: String, ) { val dashboardRequest = PutDashboardRequest { dashboardName = dashboardNameVal dashboardBody = readFileAsString(fileNameVal) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putDashboard(dashboardRequest) println("$dashboardNameVal was successfully updated.") } } suspend fun createNewCustomMetric(dataPoint: Double) { val dimension = Dimension { name = "UNIQUE_PAGES" value = "URLS" } // Set an Instant object. val time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT) val instant = Instant.parse(time) val datum = MetricDatum { metricName = "PAGES_VISITED" unit = StandardUnit.None value = dataPoint timestamp = aws.smithy.kotlin.runtime.time .Instant(instant) dimensions = listOf(dimension) } val request = Learn the basics 2940 Amazon CloudWatch User Guide PutMetricDataRequest { namespace = "SITE/TRAFFIC" metricData = listOf(datum) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putMetricData(request) println("Added metric values for for metric PAGES_VISITED") } } suspend fun listDashboards() { CloudWatchClient { region
acw-ug-833
acw-ug.pdf
833
} } suspend fun createNewCustomMetric(dataPoint: Double) { val dimension = Dimension { name = "UNIQUE_PAGES" value = "URLS" } // Set an Instant object. val time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT) val instant = Instant.parse(time) val datum = MetricDatum { metricName = "PAGES_VISITED" unit = StandardUnit.None value = dataPoint timestamp = aws.smithy.kotlin.runtime.time .Instant(instant) dimensions = listOf(dimension) } val request = Learn the basics 2940 Amazon CloudWatch User Guide PutMetricDataRequest { namespace = "SITE/TRAFFIC" metricData = listOf(datum) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putMetricData(request) println("Added metric values for for metric PAGES_VISITED") } } suspend fun listDashboards() { CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient .listDashboardsPaginated({}) .transform { it.dashboardEntries?.forEach { obj -> emit(obj) } } .collect { obj -> println("Name is ${obj.dashboardName}") println("Dashboard ARN is ${obj.dashboardArn}") } } } suspend fun createDashboardWithMetrics( dashboardNameVal: String, fileNameVal: String, ) { val dashboardRequest = PutDashboardRequest { dashboardName = dashboardNameVal dashboardBody = readFileAsString(fileNameVal) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.putDashboard(dashboardRequest) println("$dashboardNameVal was successfully created.") val messages = response.dashboardValidationMessages if (messages != null) { if (messages.isEmpty()) { println("There are no messages in the new Dashboard") } else { for (message in messages) { println("Message is: ${message.message}") } Learn the basics 2941 Amazon CloudWatch User Guide } } } } fun readFileAsString(file: String): String = String(Files.readAllBytes(Paths.get(file))) suspend fun getMetricStatistics(costDateWeek: String?) { val start = Instant.parse(costDateWeek) val endDate = Instant.now() val dimension = Dimension { name = "Currency" value = "USD" } val dimensionList: MutableList<Dimension> = ArrayList() dimensionList.add(dimension) val statisticsRequest = GetMetricStatisticsRequest { metricName = "EstimatedCharges" namespace = "AWS/Billing" dimensions = dimensionList statistics = listOf(Statistic.Maximum) startTime = aws.smithy.kotlin.runtime.time .Instant(start) endTime = aws.smithy.kotlin.runtime.time .Instant(endDate) period = 86400 } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricStatistics(statisticsRequest) val data: List<Datapoint>? = response.datapoints if (data != null) { if (!data.isEmpty()) { for (datapoint in data) { println("Timestamp: ${datapoint.timestamp} Maximum value: ${datapoint.maximum}") } } else { Learn the basics 2942 Amazon CloudWatch User Guide println("The returned data list is empty") } } } } suspend fun getAndDisplayMetricStatistics( nameSpaceVal: String, metVal: String, metricOption: String, date: String, myDimension: Dimension, ) { val start = Instant.parse(date) val endDate = Instant.now() val statisticsRequest = GetMetricStatisticsRequest { endTime = aws.smithy.kotlin.runtime.time .Instant(endDate) startTime = aws.smithy.kotlin.runtime.time .Instant(start) dimensions = listOf(myDimension) metricName = metVal namespace = nameSpaceVal period = 86400 statistics = listOf(Statistic.fromValue(metricOption)) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricStatistics(statisticsRequest) val data = response.datapoints if (data != null) { if (data.isNotEmpty()) { for (datapoint in data) { println("Timestamp: ${datapoint.timestamp} Maximum value: ${datapoint.maximum}") } } else { println("The returned data list is empty") } } } Learn the basics 2943 Amazon CloudWatch } User Guide suspend fun listMets(namespaceVal: String?): ArrayList<String>? { val metList = ArrayList<String>() val request = ListMetricsRequest { namespace = namespaceVal } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val reponse = cwClient.listMetrics(request) reponse.metrics?.forEach { metrics -> val data = metrics.metricName if (!metList.contains(data)) { metList.add(data!!) } } } return metList } suspend fun getSpecificMet(namespaceVal: String?): Dimension? { val request = ListMetricsRequest { namespace = namespaceVal } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.listMetrics(request) val myList = response.metrics if (myList != null) { return myList[0].dimensions?.get(0) } } return null } suspend fun listNameSpaces(): ArrayList<String> { val nameSpaceList = ArrayList<String>() CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.listMetrics(ListMetricsRequest {}) response.metrics?.forEach { metrics -> val data = metrics.namespace if (!nameSpaceList.contains(data)) { nameSpaceList.add(data!!) } Learn the basics 2944 Amazon CloudWatch User Guide } } return nameSpaceList } • For API details, see the following topics in AWS SDK for Kotlin API reference. • DeleteAlarms • DeleteAnomalyDetector • DeleteDashboards • DescribeAlarmHistory • DescribeAlarms • DescribeAlarmsForMetric • DescribeAnomalyDetectors • GetMetricData • GetMetricStatistics • GetMetricWidgetImage • ListMetrics • PutAnomalyDetector • PutDashboard • PutMetricAlarm • PutMetricData For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions for CloudWatch using AWS SDKs The following code examples demonstrate how to perform individual CloudWatch actions with AWS SDKs. Each example includes a link to GitHub, where you can find instructions for setting up and running the code. These excerpts call the CloudWatch API and are code excerpts from larger programs that must be run in context. You can see actions in context in Scenarios for CloudWatch using AWS SDKs . Actions 2945 Amazon CloudWatch User Guide The following examples include only the most commonly used actions. For a complete list, see the Amazon CloudWatch API Reference. Examples • Use DeleteAlarms with an AWS SDK or CLI • Use DeleteAnomalyDetector with an AWS SDK or CLI • Use DeleteDashboards with an AWS SDK or CLI • Use DescribeAlarmHistory with an AWS SDK
acw-ug-834
acw-ug.pdf
834
setting up and running the code. These excerpts call the CloudWatch API and are code excerpts from larger programs that must be run in context. You can see actions in context in Scenarios for CloudWatch using AWS SDKs . Actions 2945 Amazon CloudWatch User Guide The following examples include only the most commonly used actions. For a complete list, see the Amazon CloudWatch API Reference. Examples • Use DeleteAlarms with an AWS SDK or CLI • Use DeleteAnomalyDetector with an AWS SDK or CLI • Use DeleteDashboards with an AWS SDK or CLI • Use DescribeAlarmHistory with an AWS SDK or CLI • Use DescribeAlarms with an AWS SDK or CLI • Use DescribeAlarmsForMetric with an AWS SDK or CLI • Use DescribeAnomalyDetectors with an AWS SDK or CLI • Use DisableAlarmActions with an AWS SDK or CLI • Use EnableAlarmActions with an AWS SDK or CLI • Use GetDashboard with an AWS SDK or CLI • Use GetMetricData with an AWS SDK or CLI • Use GetMetricStatistics with an AWS SDK or CLI • Use GetMetricWidgetImage with an AWS SDK or CLI • Use ListDashboards with an AWS SDK or CLI • Use ListMetrics with an AWS SDK or CLI • Use PutAnomalyDetector with an AWS SDK or CLI • Use PutDashboard with an AWS SDK or CLI • Use PutMetricAlarm with an AWS SDK or CLI • Use PutMetricData with an AWS SDK or CLI Use DeleteAlarms with an AWS SDK or CLI The following code examples show how to use DeleteAlarms. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Learn the basics • Get started with alarms Actions 2946 Amazon CloudWatch • Manage metrics and alarms .NET SDK for .NET Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Delete a list of alarms from CloudWatch. /// </summary> /// <param name="alarmNames">A list of names of alarms to delete.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteAlarms(List<string> alarmNames) { var deleteAlarmsResult = await _amazonCloudWatch.DeleteAlarmsAsync( new DeleteAlarmsRequest() { AlarmNames = alarmNames }); return deleteAlarmsResult.HttpStatusCode == HttpStatusCode.OK; } • For API details, see DeleteAlarms in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 2947 Amazon CloudWatch User Guide Include the required files. #include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/DeleteAlarmsRequest.h> #include <iostream> Delete the alarm. Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::DeleteAlarmsRequest request; request.AddAlarmNames(alarm_name); auto outcome = cw.DeleteAlarms(request); if (!outcome.IsSuccess()) { std::cout << "Failed to delete CloudWatch alarm:" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully deleted CloudWatch alarm " << alarm_name << std::endl; } • For API details, see DeleteAlarms in AWS SDK for C++ API Reference. CLI AWS CLI To delete an alarm The following example uses the delete-alarms command to delete the Amazon CloudWatch alarm named "myalarm": aws cloudwatch delete-alarms --alarm-names myalarm Output: Actions 2948 Amazon CloudWatch User Guide This command returns to the prompt if successful. • For API details, see DeleteAlarms in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Deletes a CloudWatch alarm. * * @param alarmName the name of the alarm to be deleted * @return a {@link CompletableFuture} representing the asynchronous operation to delete the alarm * the {@link DeleteAlarmsResponse} is returned when the operation completes successfully, * or a {@link RuntimeException} is thrown if the operation fails */ public CompletableFuture<DeleteAlarmsResponse> deleteCWAlarmAsync(String alarmName) { DeleteAlarmsRequest request = DeleteAlarmsRequest.builder() .alarmNames(alarmName) .build(); return getAsyncClient().deleteAlarms(request) .whenComplete((response, exception) -> { if (exception != null) { throw new RuntimeException("Failed to delete the alarm:{} " + alarmName, exception); } else { logger.info("Successfully deleted alarm {} ", alarmName); } }); } Actions 2949 Amazon CloudWatch User Guide • For API details, see DeleteAlarms in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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
acw-ug-835
acw-ug.pdf
835
complete example and learn how to set up and run in the AWS 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({}); Actions 2950 Amazon CloudWatch User Guide • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DeleteAlarms in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DeleteAlarms in AWS SDK for JavaScript API Reference. Actions 2951 Amazon CloudWatch Kotlin SDK for Kotlin Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun deleteAlarm(alarmNameVal: String) { val request = DeleteAlarmsRequest { alarmNames = listOf(alarmNameVal) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.deleteAlarms(request) println("Successfully deleted alarm $alarmNameVal") } } • For API details, see DeleteAlarms in AWS SDK for Kotlin API reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ Actions 2952 Amazon CloudWatch User Guide :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def delete_metric_alarms(self, metric_namespace, metric_name): """ Deletes all of the alarms that are currently watching the specified metric. :param metric_namespace: The namespace of the metric. :param metric_name: The name of the metric. """ try: metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name) metric.alarms.delete() logger.info( "Deleted alarms for metric %s.%s.", metric_namespace, metric_name ) except ClientError: logger.exception( "Couldn't delete alarms for metric %s.%s.", metric_namespace, metric_name, ) raise • For API details, see DeleteAlarms in AWS SDK for Python (Boto3) API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 2953 Amazon CloudWatch User Guide TRY. lo_cwt->deletealarms( it_alarmnames = it_alarm_names ). MESSAGE 'Alarms deleted.' TYPE 'I'. CATCH /aws1/cx_cwtresourcenotfound. MESSAGE 'Resource being accessed is not found.' TYPE 'E'. ENDTRY. • For API details, see DeleteAlarms in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteAnomalyDetector with an AWS SDK or CLI The following code examples show how to use DeleteAnomalyDetector. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Delete a single metric anomaly detector. /// </summary> /// <param name="anomalyDetector">The anomaly detector to delete.</param> /// <returns>True if successful.</returns> Actions 2954 Amazon CloudWatch User Guide public async Task<bool> DeleteAnomalyDetector(SingleMetricAnomalyDetector anomalyDetector) { var deleteAnomalyDetectorResponse = await _amazonCloudWatch.DeleteAnomalyDetectorAsync( new DeleteAnomalyDetectorRequest() { SingleMetricAnomalyDetector = anomalyDetector }); return deleteAnomalyDetectorResponse.HttpStatusCode == HttpStatusCode.OK; } • For API details, see DeleteAnomalyDetector in AWS SDK for .NET API Reference. CLI AWS CLI To delete a specified anomaly detection model The following delete-anomaly-detector example deletes an anomaly detector model in the specified account. aws cloudwatch delete-anomaly-detector \ --namespace AWS/Logs \ --metric-name IncomingBytes \ --stat SampleCount This command produces no output. For more information, see Deleting an anomaly detection model in the Amazon CloudWatch User Guide. • For API details, see DeleteAnomalyDetector in AWS CLI Command Reference. Actions 2955 Amazon CloudWatch Java SDK for Java 2.x Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Deletes
acw-ug-836
acw-ug.pdf
836
To delete a specified anomaly detection model The following delete-anomaly-detector example deletes an anomaly detector model in the specified account. aws cloudwatch delete-anomaly-detector \ --namespace AWS/Logs \ --metric-name IncomingBytes \ --stat SampleCount This command produces no output. For more information, see Deleting an anomaly detection model in the Amazon CloudWatch User Guide. • For API details, see DeleteAnomalyDetector in AWS CLI Command Reference. Actions 2955 Amazon CloudWatch Java SDK for Java 2.x Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Deletes an Anomaly Detector. * * @param fileName the name of the file containing the Anomaly Detector configuration * @return a CompletableFuture that represents the asynchronous deletion of the Anomaly Detector */ public CompletableFuture<DeleteAnomalyDetectorResponse> deleteAnomalyDetectorAsync(String fileName) { CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); return new ObjectMapper().readTree(parser); // Return the root node } catch (IOException e) { throw new RuntimeException("Failed to read or parse the file", e); } }); return readFileFuture.thenCompose(rootNode -> { String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder() .metricName(customMetricName) Actions 2956 Amazon CloudWatch User Guide .namespace(customMetricNamespace) .stat("Maximum") .build(); DeleteAnomalyDetectorRequest request = DeleteAnomalyDetectorRequest.builder() .singleMetricAnomalyDetector(singleMetricAnomalyDetector) .build(); return getAsyncClient().deleteAnomalyDetector(request); }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Failed to delete the Anomaly Detector", exception); } else { logger.info("Successfully deleted the Anomaly Detector."); } }); } • For API details, see DeleteAnomalyDetector in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun deleteAnomalyDetector(fileName: String) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() val singleMetricAnomalyDetectorVal = Actions 2957 Amazon CloudWatch User Guide SingleMetricAnomalyDetector { metricName = customMetricName namespace = customMetricNamespace stat = "Maximum" } val request = DeleteAnomalyDetectorRequest { singleMetricAnomalyDetector = singleMetricAnomalyDetectorVal } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.deleteAnomalyDetector(request) println("Successfully deleted the Anomaly Detector.") } } • For API details, see DeleteAnomalyDetector in AWS SDK for Kotlin API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteDashboards with an AWS SDK or CLI The following code examples show how to use DeleteDashboards. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics Actions 2958 Amazon CloudWatch .NET SDK for .NET Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Delete a list of CloudWatch dashboards. /// </summary> /// <param name="dashboardNames">List of dashboard names to delete.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteDashboards(List<string> dashboardNames) { var deleteDashboardsResponse = await _amazonCloudWatch.DeleteDashboardsAsync( new DeleteDashboardsRequest() { DashboardNames = dashboardNames }); return deleteDashboardsResponse.HttpStatusCode == HttpStatusCode.OK; } • For API details, see DeleteDashboards in AWS SDK for .NET API Reference. CLI AWS CLI To delete specified dashboards The following delete-dashboards example deletes two dashboards named Dashboard- A and Dashboard-B in the specified account. aws cloudwatch delete-dashboards \ --dashboard-names Dashboard-A Dashboard-B Actions 2959 Amazon CloudWatch User Guide This command produces no output. For more information, see Amazon CloudWatch dashboards in the Amazon CloudWatch User Guide. • For API details, see DeleteDashboards in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Deletes the specified dashboard. * * @param dashboardName the name of the dashboard to be deleted * @return a {@link CompletableFuture} representing the asynchronous operation of deleting the dashboard * @throws RuntimeException if the dashboard deletion fails */ public CompletableFuture<DeleteDashboardsResponse> deleteDashboardAsync(String dashboardName) { DeleteDashboardsRequest dashboardsRequest = DeleteDashboardsRequest.builder() .dashboardNames(dashboardName) .build(); return getAsyncClient().deleteDashboards(dashboardsRequest) .whenComplete((response, exception) -> { if (exception != null) { throw new RuntimeException("Failed to delete the dashboard: " + dashboardName, exception); } else { logger.info("{} was successfully deleted.", dashboardName); } }); } Actions 2960 Amazon CloudWatch User Guide • For API details, see DeleteDashboards in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun deleteDashboard(dashboardName: String) { val dashboardsRequest = DeleteDashboardsRequest { dashboardNames = listOf(dashboardName) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.deleteDashboards(dashboardsRequest) println("$dashboardName was successfully deleted.") } } • For API details, see DeleteDashboards in
acw-ug-837
acw-ug.pdf
837
dashboard: " + dashboardName, exception); } else { logger.info("{} was successfully deleted.", dashboardName); } }); } Actions 2960 Amazon CloudWatch User Guide • For API details, see DeleteDashboards in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun deleteDashboard(dashboardName: String) { val dashboardsRequest = DeleteDashboardsRequest { dashboardNames = listOf(dashboardName) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.deleteDashboards(dashboardsRequest) println("$dashboardName was successfully deleted.") } } • For API details, see DeleteDashboards in AWS SDK for Kotlin API reference. PowerShell Tools for PowerShell Example 1: Deletes the specified dashboard, promoting for confirmation before proceeding. To bypass confirmation add the -Force switch to the command. Remove-CWDashboard -DashboardName Dashboard1 • For API details, see DeleteDashboards in AWS Tools for PowerShell Cmdlet Reference. Actions 2961 Amazon CloudWatch User Guide For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAlarmHistory with an AWS SDK or CLI The following code examples show how to use DescribeAlarmHistory. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Describe the history of an alarm for a number of days in the past. /// </summary> /// <param name="alarmName">The name of the alarm.</param> /// <param name="historyDays">The number of days in the past.</param> /// <returns>The list of alarm history data.</returns> public async Task<List<AlarmHistoryItem>> DescribeAlarmHistory(string alarmName, int historyDays) { List<AlarmHistoryItem> alarmHistory = new List<AlarmHistoryItem>(); var paginatedAlarmHistory = _amazonCloudWatch.Paginators.DescribeAlarmHistory( new DescribeAlarmHistoryRequest() { AlarmName = alarmName, EndDateUtc = DateTime.UtcNow, HistoryItemType = HistoryItemType.StateUpdate, StartDateUtc = DateTime.UtcNow.AddDays(-historyDays) Actions 2962 Amazon CloudWatch }); User Guide await foreach (var data in paginatedAlarmHistory.AlarmHistoryItems) { alarmHistory.Add(data); } return alarmHistory; } • For API details, see DescribeAlarmHistory in AWS SDK for .NET API Reference. CLI AWS CLI To retrieve history for an alarm The following example uses the describe-alarm-history command to retrieve history for the Amazon CloudWatch alarm named "myalarm": aws cloudwatch describe-alarm-history --alarm-name "myalarm" --history-item- type StateUpdate Output: { "AlarmHistoryItems": [ { "Timestamp": "2014-04-09T18:59:06.442Z", "HistoryItemType": "StateUpdate", "AlarmName": "myalarm", "HistoryData": "{\"version\":\"1.0\",\"oldState\":{\"stateValue \":\"ALARM\",\"stateReason\":\"testing purposes\"},\"newState\":{\"stateValue \":\"OK\",\"stateReason\":\"Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.958, 40.292].\",\"stateReasonData\":{\"version\":\"1.0\",\"queryDate\": \"2014-04-09T18:59:06.419+0000\",\"startDate\":\"2014-04-09T18:44:00.000+0000\", \"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.958,40.292], \"threshold\":70.0}}}", "HistorySummary": "Alarm updated from ALARM to OK" }, Actions 2963 Amazon CloudWatch { User Guide "Timestamp": "2014-04-09T18:59:05.805Z", "HistoryItemType": "StateUpdate", "AlarmName": "myalarm", "HistoryData": "{\"version\":\"1.0\",\"oldState\":{\"stateValue \":\"OK\",\"stateReason\":\"Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.839999999999996, 39.714].\",\"stateReasonData\":{\"version\": \"1.0\",\"queryDate\":\"2014-03-11T22:45:41.569+0000\",\"startDate\": \"2014-03-11T22:30:00.000+0000\",\"statistic\":\"Average\",\"period\":300, \"recentDatapoints\":[38.839999999999996,39.714],\"threshold\":70.0}},\"newState \":{\"stateValue\":\"ALARM\",\"stateReason\":\"testing purposes\"}}", "HistorySummary": "Alarm updated from OK to ALARM" } ] } • For API details, see DescribeAlarmHistory in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Retrieves the alarm history for a given alarm name and date range. * * @param fileName the path to the JSON file containing the alarm name * @param date the date to start the alarm history search (in the format "yyyy-MM-dd'T'HH:mm:ss'Z'") * @return a {@code CompletableFuture<Void>} that completes when the alarm history has been retrieved and processed */ public CompletableFuture<Void> getAlarmHistoryAsync(String fileName, String date) { Actions 2964 Amazon CloudWatch User Guide CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); return rootNode.findValue("exampleAlarmName").asText(); // Return alarmName from the JSON file } catch (IOException e) { throw new RuntimeException("Failed to read or parse the file", e); } }); // Use the alarm name to describe alarm history with a paginator. return readFileFuture.thenCompose(alarmName -> { try { Instant start = Instant.parse(date); Instant endDate = Instant.now(); DescribeAlarmHistoryRequest historyRequest = DescribeAlarmHistoryRequest.builder() .startDate(start) .endDate(endDate) .alarmName(alarmName) .historyItemType(HistoryItemType.ACTION) .build(); // Use the paginator to paginate through alarm history pages. DescribeAlarmHistoryPublisher historyPublisher = getAsyncClient().describeAlarmHistoryPaginator(historyRequest); CompletableFuture<Void> future = historyPublisher .subscribe(response -> response.alarmHistoryItems().forEach(item -> { logger.info("History summary: {}", item.historySummary()); logger.info("Timestamp: {}", item.timestamp()); })) .whenComplete((result, exception) -> { if (exception != null) { logger.error("Error occurred while getting alarm history: " + exception.getMessage(), exception); } else { Actions 2965 Amazon CloudWatch User Guide logger.info("Successfully retrieved all alarm history."); } }); // Return the future to the calling code for further handling return future; } catch (Exception e) { throw new RuntimeException("Failed to process alarm history", e); } }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error completing alarm history processing", exception); } }); } • For API details, see
acw-ug-838
acw-ug.pdf
838
.subscribe(response -> response.alarmHistoryItems().forEach(item -> { logger.info("History summary: {}", item.historySummary()); logger.info("Timestamp: {}", item.timestamp()); })) .whenComplete((result, exception) -> { if (exception != null) { logger.error("Error occurred while getting alarm history: " + exception.getMessage(), exception); } else { Actions 2965 Amazon CloudWatch User Guide logger.info("Successfully retrieved all alarm history."); } }); // Return the future to the calling code for further handling return future; } catch (Exception e) { throw new RuntimeException("Failed to process alarm history", e); } }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error completing alarm history processing", exception); } }); } • For API details, see DescribeAlarmHistory in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun getAlarmHistory( fileName: String, date: String, ) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val alarmNameVal = rootNode.findValue("exampleAlarmName").asText() val start = Instant.parse(date) val endDateVal = Instant.now() Actions 2966 Amazon CloudWatch User Guide val historyRequest = DescribeAlarmHistoryRequest { startDate = aws.smithy.kotlin.runtime.time .Instant(start) endDate = aws.smithy.kotlin.runtime.time .Instant(endDateVal) alarmName = alarmNameVal historyItemType = HistoryItemType.Action } CloudWatchClient { credentialsProvider = EnvironmentCredentialsProvider() region = "us-east-1" }.use { cwClient -> val response = cwClient.describeAlarmHistory(historyRequest) val historyItems = response.alarmHistoryItems if (historyItems != null) { if (historyItems.isEmpty()) { println("No alarm history data found for $alarmNameVal.") } else { for (item in historyItems) { println("History summary ${item.historySummary}") println("Time stamp: ${item.timestamp}") } } } } } • For API details, see DescribeAlarmHistory in AWS SDK for Kotlin API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAlarms with an AWS SDK or CLI The following code examples show how to use DescribeAlarms. Actions 2967 Amazon CloudWatch User Guide Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Learn the basics • Get started with alarms .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Describe the current alarms, optionally filtered by state. /// </summary> /// <param name="stateValue">Optional filter for alarm state.</param> /// <returns>The list of alarm data.</returns> public async Task<List<MetricAlarm>> DescribeAlarms(StateValue? stateValue = null) { List<MetricAlarm> alarms = new List<MetricAlarm>(); var paginatedDescribeAlarms = _amazonCloudWatch.Paginators.DescribeAlarms( new DescribeAlarmsRequest() { StateValue = stateValue }); await foreach (var data in paginatedDescribeAlarms.MetricAlarms) { alarms.Add(data); } return alarms; } • For API details, see DescribeAlarms in AWS SDK for .NET API Reference. Actions 2968 Amazon CloudWatch CLI AWS CLI User Guide To list information about an alarm The following example uses the describe-alarms command to provide information about the alarm named "myalarm": aws cloudwatch describe-alarms --alarm-names "myalarm" Output: { "MetricAlarms": [ { "EvaluationPeriods": 2, "AlarmArn": "arn:aws:cloudwatch:us- east-1:123456789012:alarm:myalarm", "StateUpdatedTimestamp": "2014-04-09T18:59:06.442Z", "AlarmConfigurationUpdatedTimestamp": "2012-12-27T00:49:54.032Z", "ComparisonOperator": "GreaterThanThreshold", "AlarmActions": [ "arn:aws:sns:us-east-1:123456789012:myHighCpuAlarm" ], "Namespace": "AWS/EC2", "AlarmDescription": "CPU usage exceeds 70 percent", "StateReasonData": "{\"version\":\"1.0\",\"queryDate\": \"2014-04-09T18:59:06.419+0000\",\"startDate\":\"2014-04-09T18:44:00.000+0000\", \"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.958,40.292], \"threshold\":70.0}", "Period": 300, "StateValue": "OK", "Threshold": 70.0, "AlarmName": "myalarm", "Dimensions": [ { "Name": "InstanceId", "Value": "i-0c986c72" } ], "Statistic": "Average", Actions 2969 Amazon CloudWatch User Guide "StateReason": "Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.958, 40.292].", "InsufficientDataActions": [], "OKActions": [], "ActionsEnabled": true, "MetricName": "CPUUtilization" } ] } • For API details, see DescribeAlarms in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Describes the CloudWatch alarms of the 'METRIC_ALARM' type. * * @return a {@link CompletableFuture} that represents the asynchronous operation * of describing the CloudWatch alarms. The future completes when the * operation is finished, either successfully or with an error. */ public CompletableFuture<Void> describeAlarmsAsync() { List<AlarmType> typeList = new ArrayList<>(); typeList.add(AlarmType.METRIC_ALARM); DescribeAlarmsRequest alarmsRequest = DescribeAlarmsRequest.builder() .alarmTypes(typeList) .maxRecords(10) .build(); return getAsyncClient().describeAlarms(alarmsRequest) .thenAccept(response -> { List<MetricAlarm> alarmList = response.metricAlarms(); Actions 2970 Amazon CloudWatch User Guide for (MetricAlarm alarm : alarmList) { logger.info("Alarm name: {}", alarm.alarmName()); logger.info("Alarm description: {} ", alarm.alarmDescription()); } }) .whenComplete((response, ex) -> { if (ex != null) { logger.info("Failed to describe alarms: {}", ex.getMessage()); } else { logger.info("Successfully described alarms."); } }); } • For API details, see DescribeAlarms in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun describeAlarms() { val typeList = ArrayList<AlarmType>() typeList.add(AlarmType.MetricAlarm) val alarmsRequest = DescribeAlarmsRequest { alarmTypes = typeList maxRecords = 10 } CloudWatchClient { region
acw-ug-839
acw-ug.pdf
839
logger.info("Alarm name: {}", alarm.alarmName()); logger.info("Alarm description: {} ", alarm.alarmDescription()); } }) .whenComplete((response, ex) -> { if (ex != null) { logger.info("Failed to describe alarms: {}", ex.getMessage()); } else { logger.info("Successfully described alarms."); } }); } • For API details, see DescribeAlarms in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun describeAlarms() { val typeList = ArrayList<AlarmType>() typeList.add(AlarmType.MetricAlarm) val alarmsRequest = DescribeAlarmsRequest { alarmTypes = typeList maxRecords = 10 } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.describeAlarms(alarmsRequest) response.metricAlarms?.forEach { alarm -> println("Alarm name: ${alarm.alarmName}") Actions 2971 Amazon CloudWatch User Guide println("Alarm description: ${alarm.alarmDescription}") } } } • For API details, see DescribeAlarms in AWS SDK for Kotlin API reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-cloudwatch' # Lists the names of available Amazon CloudWatch alarms. # # @param cloudwatch_client [Aws::CloudWatch::Client] # An initialized CloudWatch client. # @example # list_alarms(Aws::CloudWatch::Client.new(region: 'us-east-1')) def list_alarms(cloudwatch_client) response = cloudwatch_client.describe_alarms if response.metric_alarms.count.positive? response.metric_alarms.each do |alarm| puts alarm.alarm_name end else puts 'No alarms found.' end rescue StandardError => e puts "Error getting information about alarms: #{e.message}" end Actions 2972 Amazon CloudWatch User Guide • For API details, see DescribeAlarms in AWS SDK for Ruby API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. oo_result = lo_cwt->describealarms( " oo_result is returned for testing purposes. " it_alarmnames = it_alarm_names ). MESSAGE 'Alarms retrieved.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception- >av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY. • For API details, see DescribeAlarms in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAlarmsForMetric with an AWS SDK or CLI The following code examples show how to use DescribeAlarmsForMetric. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Learn the basics • Manage metrics and alarms Actions 2973 Amazon CloudWatch .NET SDK for .NET Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Describe the current alarms for a specific metric. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricName">The name of the metric.</param> /// <returns>The list of alarm data.</returns> public async Task<List<MetricAlarm>> DescribeAlarmsForMetric(string metricNamespace, string metricName) { var alarmsResult = await _amazonCloudWatch.DescribeAlarmsForMetricAsync( new DescribeAlarmsForMetricRequest() { Namespace = metricNamespace, MetricName = metricName }); return alarmsResult.MetricAlarms; } • For API details, see DescribeAlarmsForMetric in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 2974 Amazon CloudWatch User Guide Include the required files. #include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/DescribeAlarmsRequest.h> #include <aws/monitoring/model/DescribeAlarmsResult.h> #include <iomanip> #include <iostream> Describe the alarms. Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::DescribeAlarmsRequest request; request.SetMaxRecords(1); bool done = false; bool header = false; while (!done) { auto outcome = cw.DescribeAlarms(request); if (!outcome.IsSuccess()) { std::cout << "Failed to describe CloudWatch alarms:" << outcome.GetError().GetMessage() << std::endl; break; } if (!header) { std::cout << std::left << std::setw(32) << "Name" << std::setw(64) << "Arn" << std::setw(64) << "Description" << std::setw(20) << "LastUpdated" << std::endl; header = true; } const auto &alarms = outcome.GetResult().GetMetricAlarms(); for (const auto &alarm : alarms) { std::cout << std::left << Actions 2975 Amazon CloudWatch User Guide std::setw(32) << alarm.GetAlarmName() << std::setw(64) << alarm.GetAlarmArn() << std::setw(64) << alarm.GetAlarmDescription() << std::setw(20) << alarm.GetAlarmConfigurationUpdatedTimestamp().ToGmtString( SIMPLE_DATE_FORMAT_STR) << std::endl; } const auto &next_token = outcome.GetResult().GetNextToken(); request.SetNextToken(next_token); done = next_token.empty(); } • For API details, see DescribeAlarmsForMetric in AWS SDK for C++ API Reference. CLI AWS CLI To display information about alarms associated with a metric The following example uses the describe-alarms-for-metric command to display information about any alarms associated with the Amazon EC2 CPUUtilization metric and the instance with the ID i-0c986c72.: aws cloudwatch describe-alarms-for-metric --metric-name CPUUtilization -- namespace AWS/EC2 --dimensions Name=InstanceId,Value=i-0c986c72 Output: { "MetricAlarms": [ { "EvaluationPeriods": 10, "AlarmArn": "arn:aws:cloudwatch:us- east-1:111122223333:alarm:myHighCpuAlarm2", "StateUpdatedTimestamp": "2013-10-30T03:03:51.479Z", "AlarmConfigurationUpdatedTimestamp": "2013-10-30T03:03:50.865Z", "ComparisonOperator": "GreaterThanOrEqualToThreshold", "AlarmActions": [ Actions 2976 Amazon CloudWatch User Guide "arn:aws:sns:us-east-1:111122223333:NotifyMe" ], "Namespace": "AWS/EC2", "AlarmDescription": "CPU usage exceeds 70 percent", "StateReasonData": "{\"version\":\"1.0\",\"queryDate\": \"2013-10-30T03:03:51.479+0000\",\"startDate\":\"2013-10-30T02:08:00.000+0000\", \"statistic\":\"Average\",\"period\":300,\"recentDatapoints\": [40.698,39.612,42.432,39.796,38.816,42.28,42.854,40.088,40.760000000000005,41.316], \"threshold\":70.0}", "Period": 300, "StateValue": "OK", "Threshold": 70.0, "AlarmName": "myHighCpuAlarm2", "Dimensions": [ { "Name": "InstanceId",
acw-ug-840
acw-ug.pdf
840
CLI To display information about alarms associated with a metric The following example uses the describe-alarms-for-metric command to display information about any alarms associated with the Amazon EC2 CPUUtilization metric and the instance with the ID i-0c986c72.: aws cloudwatch describe-alarms-for-metric --metric-name CPUUtilization -- namespace AWS/EC2 --dimensions Name=InstanceId,Value=i-0c986c72 Output: { "MetricAlarms": [ { "EvaluationPeriods": 10, "AlarmArn": "arn:aws:cloudwatch:us- east-1:111122223333:alarm:myHighCpuAlarm2", "StateUpdatedTimestamp": "2013-10-30T03:03:51.479Z", "AlarmConfigurationUpdatedTimestamp": "2013-10-30T03:03:50.865Z", "ComparisonOperator": "GreaterThanOrEqualToThreshold", "AlarmActions": [ Actions 2976 Amazon CloudWatch User Guide "arn:aws:sns:us-east-1:111122223333:NotifyMe" ], "Namespace": "AWS/EC2", "AlarmDescription": "CPU usage exceeds 70 percent", "StateReasonData": "{\"version\":\"1.0\",\"queryDate\": \"2013-10-30T03:03:51.479+0000\",\"startDate\":\"2013-10-30T02:08:00.000+0000\", \"statistic\":\"Average\",\"period\":300,\"recentDatapoints\": [40.698,39.612,42.432,39.796,38.816,42.28,42.854,40.088,40.760000000000005,41.316], \"threshold\":70.0}", "Period": 300, "StateValue": "OK", "Threshold": 70.0, "AlarmName": "myHighCpuAlarm2", "Dimensions": [ { "Name": "InstanceId", "Value": "i-0c986c72" } ], "Statistic": "Average", "StateReason": "Threshold Crossed: 10 datapoints were not greater than or equal to the threshold (70.0). The most recent datapoints: [40.760000000000005, 41.316].", "InsufficientDataActions": [], "OKActions": [], "ActionsEnabled": true, "MetricName": "CPUUtilization" }, { "EvaluationPeriods": 2, "AlarmArn": "arn:aws:cloudwatch:us- east-1:111122223333:alarm:myHighCpuAlarm", "StateUpdatedTimestamp": "2014-04-09T18:59:06.442Z", "AlarmConfigurationUpdatedTimestamp": "2014-04-09T22:26:05.958Z", "ComparisonOperator": "GreaterThanThreshold", "AlarmActions": [ "arn:aws:sns:us-east-1:111122223333:HighCPUAlarm" ], "Namespace": "AWS/EC2", "AlarmDescription": "CPU usage exceeds 70 percent", "StateReasonData": "{\"version\":\"1.0\",\"queryDate\": \"2014-04-09T18:59:06.419+0000\",\"startDate\":\"2014-04-09T18:44:00.000+0000\", \"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.958,40.292], \"threshold\":70.0}", Actions 2977 Amazon CloudWatch User Guide "Period": 300, "StateValue": "OK", "Threshold": 70.0, "AlarmName": "myHighCpuAlarm", "Dimensions": [ { "Name": "InstanceId", "Value": "i-0c986c72" } ], "Statistic": "Average", "StateReason": "Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.958, 40.292].", "InsufficientDataActions": [], "OKActions": [], "ActionsEnabled": false, "MetricName": "CPUUtilization" } ] } • For API details, see DescribeAlarmsForMetric in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Checks for a metric alarm in AWS CloudWatch. * * @param fileName the name of the file containing the JSON configuration for the custom metric * @return a {@link CompletableFuture} that completes when the check for the metric alarm is complete */ Actions 2978 Amazon CloudWatch User Guide public CompletableFuture<Void> checkForMetricAlarmAsync(String fileName) { CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); return rootNode.toString(); // Return JSON as a string for further processing } catch (IOException e) { throw new RuntimeException("Failed to read file", e); } }); return readFileFuture.thenCompose(jsonContent -> { try { com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent); String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); DescribeAlarmsForMetricRequest metricRequest = DescribeAlarmsForMetricRequest.builder() .metricName(customMetricName) .namespace(customMetricNamespace) .build(); return checkForAlarmAsync(metricRequest, customMetricName, 10); } catch (IOException e) { throw new RuntimeException("Failed to parse JSON content", e); } }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error checking metric alarm", exception); } }); } // Recursive method to check for the alarm. Actions 2979 Amazon CloudWatch User Guide /** * Checks for the existence of an alarm asynchronously for the specified metric. * * @param metricRequest the request to describe the alarms for the specified metric * @param customMetricName the name of the custom metric to check for an alarm * @param retries the number of retries to perform if no alarm is found * @return a {@link CompletableFuture} that completes when an alarm is found or the maximum number of retries has been reached */ private static CompletableFuture<Void> checkForAlarmAsync(DescribeAlarmsForMetricRequest metricRequest, String customMetricName, int retries) { if (retries == 0) { return CompletableFuture.completedFuture(null).thenRun(() -> logger.info("No Alarm state found for {} after 10 retries.", customMetricName) ); } return (getAsyncClient().describeAlarmsForMetric(metricRequest).thenCompose(response -> { if (response.hasMetricAlarms()) { logger.info("Alarm state found for {}", customMetricName); return CompletableFuture.completedFuture(null); // Alarm found, complete the future } else { return CompletableFuture.runAsync(() -> { try { Thread.sleep(20000); logger.info("."); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while waiting to retry", e); } }).thenCompose(v -> checkForAlarmAsync(metricRequest, customMetricName, retries - 1)); // Recursive call } })); Actions 2980 Amazon CloudWatch } User Guide • For API details, see DescribeAlarmsForMetric in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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({}); Actions 2981 Amazon CloudWatch User Guide • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DescribeAlarmsForMetric in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. // Load the AWS SDK for Node.js
acw-ug-841
acw-ug.pdf
841
{ 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({}); Actions 2981 Amazon CloudWatch User Guide • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DescribeAlarmsForMetric in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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); }); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DescribeAlarmsForMetric in AWS SDK for JavaScript API Reference. Actions 2982 Amazon CloudWatch Kotlin SDK for Kotlin Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun checkForMetricAlarm(fileName: String?) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() var hasAlarm = false var retries = 10 val metricRequest = DescribeAlarmsForMetricRequest { metricName = customMetricName namespace = customMetricNamespace } CloudWatchClient { region = "us-east-1" }.use { cwClient -> while (!hasAlarm && retries > 0) { val response = cwClient.describeAlarmsForMetric(metricRequest) if (response.metricAlarms?.count()!! > 0) { hasAlarm = true } retries-- delay(20000) println(".") } if (!hasAlarm) { println("No Alarm state found for $customMetricName after 10 retries.") } else { println("Alarm state found for $customMetricName.") } } Actions 2983 Amazon CloudWatch } User Guide • For API details, see DescribeAlarmsForMetric in AWS SDK for Kotlin API reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def get_metric_alarms(self, metric_namespace, metric_name): """ Gets the alarms that are currently watching the specified metric. :param metric_namespace: The namespace of the metric. :param metric_name: The name of the metric. :returns: An iterator that yields the alarms. """ metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name) alarm_iter = metric.alarms.all() logger.info("Got alarms for metric %s.%s.", metric_namespace, metric_name) return alarm_iter Actions 2984 Amazon CloudWatch User Guide • For API details, see DescribeAlarmsForMetric in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. # # @param cloudwatch_client [Aws::CloudWatch::Client] # An initialized CloudWatch client. # @example # describe_metric_alarms(Aws::CloudWatch::Client.new(region: 'us-east-1')) def describe_metric_alarms(cloudwatch_client) response = cloudwatch_client.describe_alarms if response.metric_alarms.count.positive? response.metric_alarms.each do |alarm| puts '-' * 16 puts "Name: #{alarm.alarm_name}" puts "State value: #{alarm.state_value}" puts "State reason: #{alarm.state_reason}" puts "Metric: #{alarm.metric_name}" puts "Namespace: #{alarm.namespace}" puts "Statistic: #{alarm.statistic}" puts "Period: #{alarm.period}" puts "Unit: #{alarm.unit}" puts "Eval. periods: #{alarm.evaluation_periods}" puts "Threshold: #{alarm.threshold}" puts "Comp. operator: #{alarm.comparison_operator}" if alarm.key?(:ok_actions) && alarm.ok_actions.count.positive? puts 'OK actions:' alarm.ok_actions.each do |a| puts " #{a}" end end Actions 2985 Amazon CloudWatch User Guide if alarm.key?(:alarm_actions) && alarm.alarm_actions.count.positive? puts 'Alarm actions:' alarm.alarm_actions.each do |a| puts " #{a}" end end if alarm.key?(:insufficient_data_actions) && alarm.insufficient_data_actions.count.positive? puts 'Insufficient data actions:' alarm.insufficient_data_actions.each do |a| puts " #{a}" end end puts 'Dimensions:' if alarm.key?(:dimensions) && alarm.dimensions.count.positive? alarm.dimensions.each do |d| puts " Name: #{d.name}, Value: #{d.value}" end else puts ' None for this alarm.' end end else puts 'No alarms found.' end rescue StandardError => e puts "Error getting information about alarms: #{e.message}" end # Example usage: def run_me region = '' # Print usage information and then stop. if ARGV[0] == '--help' || ARGV[0] == '-h' puts 'Usage: ruby cw-ruby-example-show-alarms.rb REGION' puts 'Example: ruby cw-ruby-example-show-alarms.rb us-east-1' exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? region = 'us-east-1' Actions 2986 Amazon CloudWatch User Guide # Otherwise, use the values as specified at the command prompt. else region = ARGV[0] end cloudwatch_client = Aws::CloudWatch::Client.new(region: region) puts 'Available alarms:' describe_metric_alarms(cloudwatch_client) end run_me if $PROGRAM_NAME == __FILE__ • For API details, see DescribeAlarmsForMetric in AWS SDK for Ruby API Reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAnomalyDetectors with an AWS SDK or CLI The following code examples show how
acw-ug-842
acw-ug.pdf
842
ARGV.count.zero? region = 'us-east-1' Actions 2986 Amazon CloudWatch User Guide # Otherwise, use the values as specified at the command prompt. else region = ARGV[0] end cloudwatch_client = Aws::CloudWatch::Client.new(region: region) puts 'Available alarms:' describe_metric_alarms(cloudwatch_client) end run_me if $PROGRAM_NAME == __FILE__ • For API details, see DescribeAlarmsForMetric in AWS SDK for Ruby API Reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAnomalyDetectors with an AWS SDK or CLI The following code examples show how to use DescribeAnomalyDetectors. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> Actions 2987 Amazon CloudWatch User Guide /// Describe anomaly detectors for a metric and namespace. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricName">The metric of the anomaly detectors.</param> /// <returns>The list of detectors.</returns> public async Task<List<AnomalyDetector>> DescribeAnomalyDetectors(string metricNamespace, string metricName) { List<AnomalyDetector> detectors = new List<AnomalyDetector>(); var paginatedDescribeAnomalyDetectors = _amazonCloudWatch.Paginators.DescribeAnomalyDetectors( new DescribeAnomalyDetectorsRequest() { MetricName = metricName, Namespace = metricNamespace }); await foreach (var data in paginatedDescribeAnomalyDetectors.AnomalyDetectors) { detectors.Add(data); } return detectors; } • For API details, see DescribeAnomalyDetectors in AWS SDK for .NET API Reference. CLI AWS CLI To retrieve a list of anomaly detection models The following describe-anomaly-detectors example displays information about anomaly detector models that are associated with the AWS/Logs namespace in the specified account. aws cloudwatch describe-anomaly-detectors \ --namespace AWS/Logs Actions 2988 Amazon CloudWatch Output: { User Guide "AnomalyDetectors": [ { "Namespace": "AWS/Logs", "MetricName": "IncomingBytes", "Dimensions": [], "Stat": "SampleCount", "Configuration": { "ExcludedTimeRanges": [] }, "StateValue": "TRAINED", "SingleMetricAnomalyDetector": { "AccountId": "123456789012", "Namespace": "AWS/Logs", "MetricName": "IncomingBytes", "Dimensions": [], "Stat": "SampleCount" } }, { "Namespace": "AWS/Logs", "MetricName": "IncomingBytes", "Dimensions": [ { "Name": "LogGroupName", "Value": "demo" } ], "Stat": "Average", "Configuration": { "ExcludedTimeRanges": [] }, "StateValue": "PENDING_TRAINING", "SingleMetricAnomalyDetector": { "AccountId": "123456789012", "Namespace": "AWS/Logs", "MetricName": "IncomingBytes", "Dimensions": [ { "Name": "LogGroupName", "Value": "demo" } Actions 2989 Amazon CloudWatch User Guide ], "Stat": "Average" } } ] } For more information, see Using CloudWatch anomaly detection in the Amazon CloudWatch User Guide. • For API details, see DescribeAnomalyDetectors in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Describes the anomaly detectors based on the specified JSON file. * * @param fileName the name of the JSON file containing the custom metric namespace and name * @return a {@link CompletableFuture} that completes when the anomaly detectors have been described * @throws RuntimeException if there is a failure during the operation, such as when reading or parsing the JSON file, * or when describing the anomaly detectors */ public CompletableFuture<Void> describeAnomalyDetectorsAsync(String fileName) { CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); return new ObjectMapper().readTree(parser); Actions 2990 Amazon CloudWatch User Guide } catch (IOException e) { throw new RuntimeException("Failed to read or parse the file", e); } }); return readFileFuture.thenCompose(rootNode -> { try { String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); DescribeAnomalyDetectorsRequest detectorsRequest = DescribeAnomalyDetectorsRequest.builder() .maxResults(10) .metricName(customMetricName) .namespace(customMetricNamespace) .build(); return getAsyncClient().describeAnomalyDetectors(detectorsRequest).thenAccept(response -> { List<AnomalyDetector> anomalyDetectorList = response.anomalyDetectors(); for (AnomalyDetector detector : anomalyDetectorList) { logger.info("Metric name: {} ", detector.singleMetricAnomalyDetector().metricName()); logger.info("State: {} ", detector.stateValue()); } }); } catch (RuntimeException e) { throw new RuntimeException("Failed to describe anomaly detectors", e); } }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error describing anomaly detectors", exception); } }); } Actions 2991 Amazon CloudWatch User Guide • For API details, see DescribeAnomalyDetectors in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun describeAnomalyDetectors(fileName: String) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() val detectorsRequest = DescribeAnomalyDetectorsRequest { maxResults = 10 metricName = customMetricName namespace = customMetricNamespace } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.describeAnomalyDetectors(detectorsRequest) response.anomalyDetectors?.forEach { detector -> println("Metric name: ${detector.singleMetricAnomalyDetector?.metricName}") println("State: ${detector.stateValue}") } } } • For API details, see DescribeAnomalyDetectors in AWS SDK for Kotlin API reference. Actions 2992 Amazon CloudWatch User Guide For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DisableAlarmActions with
acw-ug-843
acw-ug.pdf
843
rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() val detectorsRequest = DescribeAnomalyDetectorsRequest { maxResults = 10 metricName = customMetricName namespace = customMetricNamespace } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.describeAnomalyDetectors(detectorsRequest) response.anomalyDetectors?.forEach { detector -> println("Metric name: ${detector.singleMetricAnomalyDetector?.metricName}") println("State: ${detector.stateValue}") } } } • For API details, see DescribeAnomalyDetectors in AWS SDK for Kotlin API reference. Actions 2992 Amazon CloudWatch User Guide For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DisableAlarmActions with an AWS SDK or CLI The following code examples show how to use DisableAlarmActions. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Get started with alarms • Manage metrics and alarms .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Disable the actions for a list of alarms from CloudWatch. /// </summary> /// <param name="alarmNames">A list of names of alarms.</param> /// <returns>True if successful.</returns> public async Task<bool> DisableAlarmActions(List<string> alarmNames) { var disableAlarmActionsResult = await _amazonCloudWatch.DisableAlarmActionsAsync( new DisableAlarmActionsRequest() { AlarmNames = alarmNames }); return disableAlarmActionsResult.HttpStatusCode == HttpStatusCode.OK; } Actions 2993 Amazon CloudWatch User Guide • For API details, see DisableAlarmActions in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Include the required files. #include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/DisableAlarmActionsRequest.h> #include <iostream> Disable the alarm actions. Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::DisableAlarmActionsRequest disableAlarmActionsRequest; disableAlarmActionsRequest.AddAlarmNames(alarm_name); auto disableAlarmActionsOutcome = cw.DisableAlarmActions(disableAlarmActionsRequest); if (!disableAlarmActionsOutcome.IsSuccess()) { std::cout << "Failed to disable actions for alarm " << alarm_name << ": " << disableAlarmActionsOutcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully disabled actions for alarm " << Actions 2994 Amazon CloudWatch User Guide alarm_name << std::endl; } • For API details, see DisableAlarmActions in AWS SDK for C++ API Reference. CLI AWS CLI To disable actions for an alarm The following example uses the disable-alarm-actions command to disable all actions for the alarm named myalarm.: aws cloudwatch disable-alarm-actions --alarm-names myalarm This command returns to the prompt if successful. • For API details, see DisableAlarmActions in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatch.model.DisableAlarmActionsRequest; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * Actions 2995 Amazon CloudWatch User Guide * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class DisableAlarmActions { public static void main(String[] args) { final String usage = """ Usage: <alarmName> Where: alarmName - An alarm name to disable (for example, MyAlarm). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String alarmName = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() .region(region) .build(); disableActions(cw, alarmName); cw.close(); } public static void disableActions(CloudWatchClient cw, String alarmName) { try { DisableAlarmActionsRequest request = DisableAlarmActionsRequest.builder() .alarmNames(alarmName) .build(); cw.disableAlarmActions(request); System.out.printf("Successfully disabled actions on alarm %s", alarmName); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); Actions 2996 Amazon CloudWatch User Guide System.exit(1); } } } • For API details, see DisableAlarmActions in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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. Actions 2997 Amazon CloudWatch User Guide import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({}); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DisableAlarmActions in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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"
acw-ug-844
acw-ug.pdf
844
from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({}); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DisableAlarmActions in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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); } } ); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DisableAlarmActions in AWS SDK for JavaScript API Reference. Actions 2998 Amazon CloudWatch Kotlin SDK for Kotlin Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun disableActions(alarmName: String) { val request = DisableAlarmActionsRequest { alarmNames = listOf(alarmName) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.disableAlarmActions(request) println("Successfully disabled actions on alarm $alarmName") } } • For API details, see DisableAlarmActions in AWS SDK for Kotlin API reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. Actions 2999 Amazon CloudWatch """ self.cloudwatch_resource = cloudwatch_resource User Guide def enable_alarm_actions(self, alarm_name, enable): """ Enables or disables actions on the specified alarm. Alarm actions can be used to send notifications or automate responses when an alarm enters a particular state. :param alarm_name: The name of the alarm. :param enable: When True, actions are enabled for the alarm. Otherwise, they disabled. """ try: alarm = self.cloudwatch_resource.Alarm(alarm_name) if enable: alarm.enable_actions() else: alarm.disable_actions() logger.info( "%s actions for alarm %s.", "Enabled" if enable else "Disabled", alarm_name, ) except ClientError: logger.exception( "Couldn't %s actions alarm %s.", "enable" if enable else "disable", alarm_name, ) raise • For API details, see DisableAlarmActions in AWS SDK for Python (Boto3) API Reference. Actions 3000 Amazon CloudWatch Ruby SDK for Ruby Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. # Disables an alarm in Amazon CloudWatch. # # Prerequisites. # # - The alarm to disable. # # @param cloudwatch_client [Aws::CloudWatch::Client] # An initialized CloudWatch client. # @param alarm_name [String] The name of the alarm to disable. # @return [Boolean] true if the alarm was disabled; otherwise, false. # @example # exit 1 unless alarm_actions_disabled?( # Aws::CloudWatch::Client.new(region: 'us-east-1'), # 'ObjectsInBucket' # ) def alarm_actions_disabled?(cloudwatch_client, alarm_name) cloudwatch_client.disable_alarm_actions(alarm_names: [alarm_name]) true rescue StandardError => e puts "Error disabling alarm actions: #{e.message}" false end # Example usage: def run_me alarm_name = 'ObjectsInBucket' alarm_description = 'Objects exist in this bucket for more than 1 day.' metric_name = 'NumberOfObjects' # Notify this Amazon Simple Notification Service (Amazon SNS) topic when # the alarm transitions to the ALARM state. alarm_actions = ['arn:aws:sns:us- east-1:111111111111:Default_CloudWatch_Alarms_Topic'] Actions 3001 Amazon CloudWatch User Guide namespace = 'AWS/S3' statistic = 'Average' dimensions = [ { name: "BucketName", value: "amzn-s3-demo-bucket" }, { name: 'StorageType', value: 'AllStorageTypes' } ] period = 86_400 # Daily (24 hours * 60 minutes * 60 seconds = 86400 seconds). unit = 'Count' evaluation_periods = 1 # More than one day. threshold = 1 # One object. comparison_operator = 'GreaterThanThreshold' # More than one object. # Replace us-west-2 with the AWS Region you're using for Amazon CloudWatch. region = 'us-east-1' cloudwatch_client = Aws::CloudWatch::Client.new(region: region) if alarm_created_or_updated?( cloudwatch_client, alarm_name, alarm_description, metric_name, alarm_actions, namespace, statistic, dimensions, period, unit, evaluation_periods, threshold, comparison_operator ) puts "Alarm '#{alarm_name}' created or updated." else puts "Could not create or update alarm '#{alarm_name}'." end if alarm_actions_disabled?(cloudwatch_client, alarm_name) puts "Alarm '#{alarm_name}' disabled." Actions 3002 Amazon CloudWatch else puts "Could not disable alarm '#{alarm_name}'." end end run_me if $PROGRAM_NAME == __FILE__ User Guide • For API details, see DisableAlarmActions in AWS SDK for Ruby API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. "Disables actions on the specified alarm. " TRY. lo_cwt->disablealarmactions( it_alarmnames = it_alarm_names ). MESSAGE 'Alarm actions disabled.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception- >av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY. • For API details, see DisableAlarmActions in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with
acw-ug-845
acw-ug.pdf
845
Ruby API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. "Disables actions on the specified alarm. " TRY. lo_cwt->disablealarmactions( it_alarmnames = it_alarm_names ). MESSAGE 'Alarm actions disabled.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception- >av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY. • For API details, see DisableAlarmActions in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 3003 Amazon CloudWatch User Guide Use EnableAlarmActions with an AWS SDK or CLI The following code examples show how to use EnableAlarmActions. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Manage metrics and alarms .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Enable the actions for a list of alarms from CloudWatch. /// </summary> /// <param name="alarmNames">A list of names of alarms.</param> /// <returns>True if successful.</returns> public async Task<bool> EnableAlarmActions(List<string> alarmNames) { var enableAlarmActionsResult = await _amazonCloudWatch.EnableAlarmActionsAsync( new EnableAlarmActionsRequest() { AlarmNames = alarmNames }); return enableAlarmActionsResult.HttpStatusCode == HttpStatusCode.OK; } • For API details, see EnableAlarmActions in AWS SDK for .NET API Reference. Actions 3004 Amazon CloudWatch C++ SDK for C++ Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Include the required files. #include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/EnableAlarmActionsRequest.h> #include <aws/monitoring/model/PutMetricAlarmRequest.h> #include <iostream> Enable the alarm actions. Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::PutMetricAlarmRequest request; request.SetAlarmName(alarm_name); request.SetComparisonOperator( Aws::CloudWatch::Model::ComparisonOperator::GreaterThanThreshold); request.SetEvaluationPeriods(1); request.SetMetricName("CPUUtilization"); request.SetNamespace("AWS/EC2"); request.SetPeriod(60); request.SetStatistic(Aws::CloudWatch::Model::Statistic::Average); request.SetThreshold(70.0); request.SetActionsEnabled(false); request.SetAlarmDescription("Alarm when server CPU exceeds 70%"); request.SetUnit(Aws::CloudWatch::Model::StandardUnit::Seconds); request.AddAlarmActions(actionArn); Aws::CloudWatch::Model::Dimension dimension; dimension.SetName("InstanceId"); dimension.SetValue(instanceId); request.AddDimensions(dimension); Actions 3005 Amazon CloudWatch User Guide auto outcome = cw.PutMetricAlarm(request); if (!outcome.IsSuccess()) { std::cout << "Failed to create CloudWatch alarm:" << outcome.GetError().GetMessage() << std::endl; return; } Aws::CloudWatch::Model::EnableAlarmActionsRequest enable_request; enable_request.AddAlarmNames(alarm_name); auto enable_outcome = cw.EnableAlarmActions(enable_request); if (!enable_outcome.IsSuccess()) { std::cout << "Failed to enable alarm actions:" << enable_outcome.GetError().GetMessage() << std::endl; return; } std::cout << "Successfully created alarm " << alarm_name << " and enabled actions on it." << std::endl; • For API details, see EnableAlarmActions in AWS SDK for C++ API Reference. CLI AWS CLI To enable all actions for an alarm The following example uses the enable-alarm-actions command to enable all actions for the alarm named myalarm.: aws cloudwatch enable-alarm-actions --alarm-names myalarm This command returns to the prompt if successful. • For API details, see EnableAlarmActions in AWS CLI Command Reference. Actions 3006 Amazon CloudWatch Java SDK for Java 2.x Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatch.model.EnableAlarmActionsRequest; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class EnableAlarmActions { public static void main(String[] args) { final String usage = """ Usage: <alarmName> Where: alarmName - An alarm name to enable (for example, MyAlarm). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String alarm = args[0]; Actions 3007 Amazon CloudWatch User Guide Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() .region(region) .build(); enableActions(cw, alarm); cw.close(); } public static void enableActions(CloudWatchClient cw, String alarm) { try { EnableAlarmActionsRequest request = EnableAlarmActionsRequest.builder() .alarmNames(alarm) .build(); cw.enableAlarmActions(request); System.out.printf("Successfully enabled actions on alarm %s", alarm); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see EnableAlarmActions in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Import the SDK and client modules and call the API. import { EnableAlarmActionsCommand } from "@aws-sdk/client-cloudwatch"; Actions 3008 Amazon CloudWatch User Guide 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({}); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see EnableAlarmActions in AWS SDK for JavaScript API Reference. SDK for JavaScript
acw-ug-846
acw-ug.pdf
846
User Guide 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({}); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see EnableAlarmActions in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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" }); Actions 3009 Amazon CloudWatch User Guide // 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); } }); } }); Actions 3010 Amazon CloudWatch User Guide • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see EnableAlarmActions in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun enableActions(alarm: String) { val request = EnableAlarmActionsRequest { alarmNames = listOf(alarm) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.enableAlarmActions(request) println("Successfully enabled actions on alarm $alarm") } } • For API details, see EnableAlarmActions in AWS SDK for Kotlin API reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class CloudWatchWrapper: Actions 3011 Amazon CloudWatch User Guide """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def enable_alarm_actions(self, alarm_name, enable): """ Enables or disables actions on the specified alarm. Alarm actions can be used to send notifications or automate responses when an alarm enters a particular state. :param alarm_name: The name of the alarm. :param enable: When True, actions are enabled for the alarm. Otherwise, they disabled. """ try: alarm = self.cloudwatch_resource.Alarm(alarm_name) if enable: alarm.enable_actions() else: alarm.disable_actions() logger.info( "%s actions for alarm %s.", "Enabled" if enable else "Disabled", alarm_name, ) except ClientError: logger.exception( "Couldn't %s actions alarm %s.", "enable" if enable else "disable", alarm_name, ) raise • For API details, see EnableAlarmActions in AWS SDK for Python (Boto3) API Reference. Actions 3012 Amazon CloudWatch SAP ABAP SDK for SAP ABAP Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. "Enable actions on the specified alarm." TRY. lo_cwt->enablealarmactions( it_alarmnames = it_alarm_names ). MESSAGE 'Alarm actions enabled.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception- >av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY. • For API details, see EnableAlarmActions in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetDashboard with an AWS SDK or CLI The following code examples show how to use GetDashboard. Actions 3013 Amazon CloudWatch .NET SDK for .NET Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Get information on a dashboard. /// </summary> /// <param name="dashboardName">The name of the dashboard.</param> /// <returns>A JSON object with dashboard information.</returns> public async Task<string> GetDashboard(string dashboardName) { var dashboardResponse = await _amazonCloudWatch.GetDashboardAsync( new GetDashboardRequest() { DashboardName = dashboardName }); return dashboardResponse.DashboardBody; } • For API details, see GetDashboard in AWS SDK for .NET API Reference. CLI AWS CLI To retrieve information about a Dashboard The following get-dashboard example displays information about the dashboard named Dashboard-A in the specified account. aws cloudwatch get-dashboard \ --dashboard-name Dashboard-A Actions 3014 Amazon CloudWatch Output: { User Guide "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/Dashboard-A", "DashboardBody": "{\"widgets\":[{\"type\":\"metric\",\"x\":0,\"y\":0,\"width \":6,\"height\":6,\"properties\":{\"view\":\"timeSeries\",\"stacked\":false, \"metrics\":[[\"AWS/EC2\",\"NetworkIn\",\"InstanceId\",\"i-0131f062232ade043\"], [\".\",\"NetworkOut\",\".\",\".\"]],\"region\":\"us-east-1\"}}]}", "DashboardName": "Dashboard-A" } For more information, see Amazon
acw-ug-847
acw-ug.pdf
847
<param name="dashboardName">The name of the dashboard.</param> /// <returns>A JSON object with dashboard information.</returns> public async Task<string> GetDashboard(string dashboardName) { var dashboardResponse = await _amazonCloudWatch.GetDashboardAsync( new GetDashboardRequest() { DashboardName = dashboardName }); return dashboardResponse.DashboardBody; } • For API details, see GetDashboard in AWS SDK for .NET API Reference. CLI AWS CLI To retrieve information about a Dashboard The following get-dashboard example displays information about the dashboard named Dashboard-A in the specified account. aws cloudwatch get-dashboard \ --dashboard-name Dashboard-A Actions 3014 Amazon CloudWatch Output: { User Guide "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/Dashboard-A", "DashboardBody": "{\"widgets\":[{\"type\":\"metric\",\"x\":0,\"y\":0,\"width \":6,\"height\":6,\"properties\":{\"view\":\"timeSeries\",\"stacked\":false, \"metrics\":[[\"AWS/EC2\",\"NetworkIn\",\"InstanceId\",\"i-0131f062232ade043\"], [\".\",\"NetworkOut\",\".\",\".\"]],\"region\":\"us-east-1\"}}]}", "DashboardName": "Dashboard-A" } For more information, see Amazon CloudWatch dashboards in the Amazon CloudWatch User Guide. • For API details, see GetDashboard in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: Returns the arn the body of the specified dashboard. Get-CWDashboard -DashboardName Dashboard1 Output: DashboardArn DashboardBody ------------ ------------- arn:aws:cloudwatch::123456789012:dashboard/Dashboard1 {... • For API details, see GetDashboard in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetMetricData with an AWS SDK or CLI The following code examples show how to use GetMetricData. Actions 3015 Amazon CloudWatch User Guide Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Get data for CloudWatch metrics. /// </summary> /// <param name="minutesOfData">The number of minutes of data to include.</ param> /// <param name="useDescendingTime">True to return the data descending by time.</param> /// <param name="endDateUtc">The end date for the data, in UTC.</param> /// <param name="maxDataPoints">The maximum data points to include.</param> /// <param name="dataQueries">Optional data queries to include.</param> /// <returns>A list of the requested metric data.</returns> public async Task<List<MetricDataResult>> GetMetricData(int minutesOfData, bool useDescendingTime, DateTime? endDateUtc = null, int maxDataPoints = 0, List<MetricDataQuery>? dataQueries = null) { var metricData = new List<MetricDataResult>(); // If no end time is provided, use the current time for the end time. endDateUtc ??= DateTime.UtcNow; var timeZoneOffset = TimeZoneInfo.Local.GetUtcOffset(endDateUtc.Value.ToLocalTime()); var startTimeUtc = endDateUtc.Value.AddMinutes(-minutesOfData); // The timezone string should be in the format +0000, so use the timezone offset to format it correctly. var timeZoneString = $"{timeZoneOffset.Hours:D2} {timeZoneOffset.Minutes:D2}"; var paginatedMetricData = _amazonCloudWatch.Paginators.GetMetricData( Actions 3016 Amazon CloudWatch User Guide new GetMetricDataRequest() { StartTimeUtc = startTimeUtc, EndTimeUtc = endDateUtc.Value, LabelOptions = new LabelOptions { Timezone = timeZoneString }, ScanBy = useDescendingTime ? ScanBy.TimestampDescending : ScanBy.TimestampAscending, MaxDatapoints = maxDataPoints, MetricDataQueries = dataQueries, }); await foreach (var data in paginatedMetricData.MetricDataResults) { metricData.Add(data); } return metricData; } • For API details, see GetMetricData in AWS SDK for .NET API Reference. CLI AWS CLI Example 1: To get the Average Total IOPS for the specified EC2 using math expression The following get-metric-data example retrieves CloudWatch metric values for the EC2 instance with InstanceID i-abcdef using metric math exprssion that combines EBSReadOps and EBSWriteOps metrics. aws cloudwatch get-metric-data \ --metric-data-queries file://file.json \ --start-time 2024-09-29T22:10:00Z \ --end-time 2024-09-29T22:15:00Z Contents of file.json: [ { "Id": "m3", "Expression": "(m1+m2)/300", Actions 3017 Amazon CloudWatch User Guide "Label": "Avg Total IOPS" }, { "Id": "m1", "MetricStat": { "Metric": { "Namespace": "AWS/EC2", "MetricName": "EBSReadOps", "Dimensions": [ { "Name": "InstanceId", "Value": "i-abcdef" } ] }, "Period": 300, "Stat": "Sum", "Unit": "Count" }, "ReturnData": false }, { "Id": "m2", "MetricStat": { "Metric": { "Namespace": "AWS/EC2", "MetricName": "EBSWriteOps", "Dimensions": [ { "Name": "InstanceId", "Value": "i-abcdef" } ] }, "Period": 300, "Stat": "Sum", "Unit": "Count" }, "ReturnData": false } ] Output: Actions 3018 Amazon CloudWatch User Guide { "MetricDataResults": [ { "Id": "m3", "Label": "Avg Total IOPS", "Timestamps": [ "2024-09-29T22:10:00+00:00" ], "Values": [ 96.85 ], "StatusCode": "Complete" } ], "Messages": [] } Example 2: To monitor the estimated AWS charges using CloudWatch billing metrics The following get-metric-data example retrieves EstimatedCharges CloudWatch metric from AWS/Billing namespace. aws cloudwatch get-metric-data \ --metric-data-queries '[{"Id":"m1","MetricStat":{"Metric": {"Namespace":"AWS/Billing","MetricName":"EstimatedCharges","Dimensions": [{"Name":"Currency","Value":"USD"}]},"Period":21600,"Stat":"Maximum"}}]' \ --start-time 2024-09-26T12:00:00Z \ --end-time 2024-09-26T18:00:00Z \ --region us-east-1 Output: { "MetricDataResults": [ { "Id": "m1", "Label": "EstimatedCharges", "Timestamps": [ "2024-09-26T12:00:00+00:00" ], "Values": [ 542.38 Actions 3019 Amazon CloudWatch User Guide ], "StatusCode": "Complete" } ], "Messages": [] } For more information, see Using math expressions with CloudWatch metrics in the Amazon CloudWatch User Guide. • For API details, see GetMetricData in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Retrieves custom metric data from the AWS CloudWatch service. * * @param fileName the name of the file containing the custom metric information * @return a {@link
acw-ug-848
acw-ug.pdf
848
[ 542.38 Actions 3019 Amazon CloudWatch User Guide ], "StatusCode": "Complete" } ], "Messages": [] } For more information, see Using math expressions with CloudWatch metrics in the Amazon CloudWatch User Guide. • For API details, see GetMetricData in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Retrieves custom metric data from the AWS CloudWatch service. * * @param fileName the name of the file containing the custom metric information * @return a {@link CompletableFuture} that completes when the metric data has been retrieved */ public CompletableFuture<Void> getCustomMetricDataAsync(String fileName) { CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { try { // Read values from the JSON file. JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); return rootNode.toString(); // Return JSON as a string for further processing Actions 3020 Amazon CloudWatch User Guide } catch (IOException e) { throw new RuntimeException("Failed to read file", e); } }); return readFileFuture.thenCompose(jsonContent -> { try { // Parse the JSON string to extract relevant values. com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent); String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); // Set the current time and date range for metric query. Instant nowDate = Instant.now(); long hours = 1; long minutes = 30; Instant endTime = nowDate.plus(hours, ChronoUnit.HOURS).plus(minutes, ChronoUnit.MINUTES); Metric met = Metric.builder() .metricName(customMetricName) .namespace(customMetricNamespace) .build(); MetricStat metStat = MetricStat.builder() .stat("Maximum") .period(60) // Assuming period in seconds .metric(met) .build(); MetricDataQuery dataQuery = MetricDataQuery.builder() .metricStat(metStat) .id("foo2") .returnData(true) .build(); List<MetricDataQuery> dq = new ArrayList<>(); dq.add(dataQuery); GetMetricDataRequest getMetricDataRequest = GetMetricDataRequest.builder() Actions 3021 Amazon CloudWatch User Guide .maxDatapoints(10) .scanBy(ScanBy.TIMESTAMP_DESCENDING) .startTime(nowDate) .endTime(endTime) .metricDataQueries(dq) .build(); // Call the async method for CloudWatch data retrieval. return getAsyncClient().getMetricData(getMetricDataRequest); } catch (IOException e) { throw new RuntimeException("Failed to parse JSON content", e); } }).thenAccept(response -> { List<MetricDataResult> data = response.metricDataResults(); for (MetricDataResult item : data) { logger.info("The label is: {}", item.label()); logger.info("The status code is: {}", item.statusCode().toString()); } }).exceptionally(exception -> { throw new RuntimeException("Failed to get metric data", exception); }); } • For API details, see GetMetricData in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun getCustomMetricData(fileName: String) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) Actions 3022 Amazon CloudWatch User Guide val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() // Set the date. val nowDate = Instant.now() val hours: Long = 1 val minutes: Long = 30 val date2 = nowDate.plus(hours, ChronoUnit.HOURS).plus( minutes, ChronoUnit.MINUTES, ) val met = Metric { metricName = customMetricName namespace = customMetricNamespace } val metStat = MetricStat { stat = "Maximum" period = 1 metric = met } val dataQUery = MetricDataQuery { metricStat = metStat id = "foo2" returnData = true } val dq = ArrayList<MetricDataQuery>() dq.add(dataQUery) val getMetReq = GetMetricDataRequest { maxDatapoints = 10 scanBy = ScanBy.TimestampDescending startTime = aws.smithy.kotlin.runtime.time .Instant(nowDate) endTime = Actions 3023 Amazon CloudWatch User Guide aws.smithy.kotlin.runtime.time .Instant(date2) metricDataQueries = dq } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricData(getMetReq) response.metricDataResults?.forEach { item -> println("The label is ${item.label}") println("The status code is ${item.statusCode}") } } } • For API details, see GetMetricData in AWS SDK for Kotlin API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetMetricStatistics with an AWS SDK or CLI The following code examples show how to use GetMetricStatistics. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Learn the basics • Manage metrics and alarms .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 3024 Amazon CloudWatch User Guide /// <summary> /// Get billing statistics using a call to a wrapper class. /// </summary> /// <returns>A collection of billing statistics.</returns> private static async Task<List<Datapoint>> SetupBillingStatistics() { // Make a request for EstimatedCharges with a period of one day for the past seven days. var billingStatistics = await _cloudWatchWrapper.GetMetricStatistics( "AWS/Billing", "EstimatedCharges", new List<string>() { "Maximum" }, new List<Dimension>() { new Dimension { Name = "Currency", Value = "USD" } }, 7, 86400); billingStatistics = billingStatistics.OrderBy(n => n.Timestamp).ToList(); return billingStatistics; } /// <summary> /// Wrapper to get statistics for a specific CloudWatch metric. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricName">The name of the metric.</param> /// <param name="statistics">The list of statistics to include.</param> /// <param name="dimensions">The list
acw-ug-849
acw-ug.pdf
849
statistics.</returns> private static async Task<List<Datapoint>> SetupBillingStatistics() { // Make a request for EstimatedCharges with a period of one day for the past seven days. var billingStatistics = await _cloudWatchWrapper.GetMetricStatistics( "AWS/Billing", "EstimatedCharges", new List<string>() { "Maximum" }, new List<Dimension>() { new Dimension { Name = "Currency", Value = "USD" } }, 7, 86400); billingStatistics = billingStatistics.OrderBy(n => n.Timestamp).ToList(); return billingStatistics; } /// <summary> /// Wrapper to get statistics for a specific CloudWatch metric. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricName">The name of the metric.</param> /// <param name="statistics">The list of statistics to include.</param> /// <param name="dimensions">The list of dimensions to include.</param> /// <param name="days">The number of days in the past to include.</param> /// <param name="period">The period for the data.</param> /// <returns>A list of DataPoint objects for the statistics.</returns> public async Task<List<Datapoint>> GetMetricStatistics(string metricNamespace, string metricName, List<string> statistics, List<Dimension> dimensions, int days, int period) { var metricStatistics = await _amazonCloudWatch.GetMetricStatisticsAsync( new GetMetricStatisticsRequest() { Namespace = metricNamespace, MetricName = metricName, Dimensions = dimensions, Actions 3025 Amazon CloudWatch User Guide Statistics = statistics, StartTimeUtc = DateTime.UtcNow.AddDays(-days), EndTimeUtc = DateTime.UtcNow, Period = period }); return metricStatistics.Datapoints; } • For API details, see GetMetricStatistics in AWS SDK for .NET API Reference. CLI AWS CLI To get the CPU utilization per EC2 instance The following example uses the get-metric-statistics command to get the CPU utilization for an EC2 instance with the ID i-abcdef. aws cloudwatch get-metric-statistics --metric-name CPUUtilization --start- time 2014-04-08T23:18:00Z --end-time 2014-04-09T23:18:00Z --period 3600 -- namespace AWS/EC2 --statistics Maximum --dimensions Name=InstanceId,Value=i- abcdef Output: { "Datapoints": [ { "Timestamp": "2014-04-09T11:18:00Z", "Maximum": 44.79, "Unit": "Percent" }, { "Timestamp": "2014-04-09T20:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T19:18:00Z", Actions 3026 Amazon CloudWatch User Guide "Maximum": 50.85, "Unit": "Percent" }, { "Timestamp": "2014-04-09T09:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T03:18:00Z", "Maximum": 76.84, "Unit": "Percent" }, { "Timestamp": "2014-04-09T21:18:00Z", "Maximum": 48.96, "Unit": "Percent" }, { "Timestamp": "2014-04-09T14:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T08:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T16:18:00Z", "Maximum": 45.55, "Unit": "Percent" }, { "Timestamp": "2014-04-09T06:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T13:18:00Z", "Maximum": 45.08, "Unit": "Percent" }, { Actions 3027 Amazon CloudWatch User Guide "Timestamp": "2014-04-09T05:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T18:18:00Z", "Maximum": 46.88, "Unit": "Percent" }, { "Timestamp": "2014-04-09T17:18:00Z", "Maximum": 52.08, "Unit": "Percent" }, { "Timestamp": "2014-04-09T07:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T02:18:00Z", "Maximum": 51.23, "Unit": "Percent" }, { "Timestamp": "2014-04-09T12:18:00Z", "Maximum": 47.67, "Unit": "Percent" }, { "Timestamp": "2014-04-08T23:18:00Z", "Maximum": 46.88, "Unit": "Percent" }, { "Timestamp": "2014-04-09T10:18:00Z", "Maximum": 51.91, "Unit": "Percent" }, { "Timestamp": "2014-04-09T04:18:00Z", "Maximum": 47.13, "Unit": "Percent" }, Actions 3028 Amazon CloudWatch { User Guide "Timestamp": "2014-04-09T15:18:00Z", "Maximum": 48.96, "Unit": "Percent" }, { "Timestamp": "2014-04-09T00:18:00Z", "Maximum": 48.16, "Unit": "Percent" }, { "Timestamp": "2014-04-09T01:18:00Z", "Maximum": 49.18, "Unit": "Percent" } ], "Label": "CPUUtilization" } Specifying multiple dimensions The following example illustrates how to specify multiple dimensions. Each dimension is specified as a Name/Value pair, with a comma between the name and the value. Multiple dimensions are separated by a space. If a single metric includes multiple dimensions, you must specify a value for every defined dimension. For more examples using the get-metric-statistics command, see Get Statistics for a Metric in the Amazon CloudWatch Developer Guide. aws cloudwatch get-metric-statistics --metric-name Buffers -- namespace MyNameSpace --dimensions Name=InstanceID,Value=i- abcdef Name=InstanceType,Value=m1.small --start-time 2016-10-15T04:00:00Z --end- time 2016-10-19T07:00:00Z --statistics Average --period 60 • For API details, see GetMetricStatistics in AWS CLI Command Reference. Actions 3029 Amazon CloudWatch Java SDK for Java 2.x Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Retrieves and displays metric statistics for the specified parameters. * * @param nameSpace the namespace for the metric * @param metVal the name of the metric * @param metricOption the statistic to retrieve for the metric (e.g., "Maximum", "Average") * @param date the date for which to retrieve the metric statistics, in the format "yyyy-MM-dd'T'HH:mm:ss'Z'" * @param myDimension the dimension(s) to filter the metric statistics by * @return a {@link CompletableFuture} that completes when the metric statistics have been retrieved and displayed */ public CompletableFuture<GetMetricStatisticsResponse> getAndDisplayMetricStatisticsAsync(String nameSpace, String metVal, String metricOption, String date, Dimension myDimension) { Instant start = Instant.parse(date); Instant endDate = Instant.now(); // Building the request for metric statistics. GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder() .endTime(endDate) .startTime(start) .dimensions(myDimension) .metricName(metVal) .namespace(nameSpace) .period(86400) // 1 day period .statistics(Statistic.fromValue(metricOption)) .build(); Actions 3030 Amazon CloudWatch User Guide return getAsyncClient().getMetricStatistics(statisticsRequest) .whenComplete((response, exception) -> { if (response != null) { List<Datapoint> data = response.datapoints(); if (!data.isEmpty()) { for (Datapoint datapoint : data) { logger.info("Timestamp: {} Maximum value: {}", datapoint.timestamp(), datapoint.maximum()); } } else { logger.info("The returned data list is empty"); } } else { logger.info("Failed to get metric statistics: {} ", exception.getMessage()); } }) .exceptionally(exception -> { throw new RuntimeException("Error while getting metric statistics: " + exception.getMessage(),
acw-ug-850
acw-ug.pdf
850
endDate = Instant.now(); // Building the request for metric statistics. GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder() .endTime(endDate) .startTime(start) .dimensions(myDimension) .metricName(metVal) .namespace(nameSpace) .period(86400) // 1 day period .statistics(Statistic.fromValue(metricOption)) .build(); Actions 3030 Amazon CloudWatch User Guide return getAsyncClient().getMetricStatistics(statisticsRequest) .whenComplete((response, exception) -> { if (response != null) { List<Datapoint> data = response.datapoints(); if (!data.isEmpty()) { for (Datapoint datapoint : data) { logger.info("Timestamp: {} Maximum value: {}", datapoint.timestamp(), datapoint.maximum()); } } else { logger.info("The returned data list is empty"); } } else { logger.info("Failed to get metric statistics: {} ", exception.getMessage()); } }) .exceptionally(exception -> { throw new RuntimeException("Error while getting metric statistics: " + exception.getMessage(), exception); }); } • For API details, see GetMetricStatistics in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun getAndDisplayMetricStatistics( nameSpaceVal: String, metVal: String, metricOption: String, Actions 3031 Amazon CloudWatch User Guide date: String, myDimension: Dimension, ) { val start = Instant.parse(date) val endDate = Instant.now() val statisticsRequest = GetMetricStatisticsRequest { endTime = aws.smithy.kotlin.runtime.time .Instant(endDate) startTime = aws.smithy.kotlin.runtime.time .Instant(start) dimensions = listOf(myDimension) metricName = metVal namespace = nameSpaceVal period = 86400 statistics = listOf(Statistic.fromValue(metricOption)) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricStatistics(statisticsRequest) val data = response.datapoints if (data != null) { if (data.isNotEmpty()) { for (datapoint in data) { println("Timestamp: ${datapoint.timestamp} Maximum value: ${datapoint.maximum}") } } else { println("The returned data list is empty") } } } } • For API details, see GetMetricStatistics in AWS SDK for Kotlin API reference. Actions 3032 Amazon CloudWatch Python SDK for Python (Boto3) Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def get_metric_statistics(self, namespace, name, start, end, period, stat_types): """ Gets statistics for a metric within a specified time span. Metrics are grouped into the specified period. :param namespace: The namespace of the metric. :param name: The name of the metric. :param start: The UTC start time of the time span to retrieve. :param end: The UTC end time of the time span to retrieve. :param period: The period, in seconds, in which to group metrics. The period must match the granularity of the metric, which depends on the metric's age. For example, metrics that are older than three hours have a one-minute granularity, so the period must be at least 60 and must be a multiple of 60. :param stat_types: The type of statistics to retrieve, such as average value or maximum value. :return: The retrieved statistics for the metric. Actions 3033 Amazon CloudWatch """ User Guide try: metric = self.cloudwatch_resource.Metric(namespace, name) stats = metric.get_statistics( StartTime=start, EndTime=end, Period=period, Statistics=stat_types ) logger.info( "Got %s statistics for %s.", len(stats["Datapoints"]), stats["Label"] ) except ClientError: logger.exception("Couldn't get statistics for %s.%s.", namespace, name) raise else: return stats • For API details, see GetMetricStatistics in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetMetricWidgetImage with an AWS SDK or CLI The following code examples show how to use GetMetricWidgetImage. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics Actions 3034 Amazon CloudWatch .NET SDK for .NET Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Get an image for a metric graphed over time. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metric">The name of the metric.</param> /// <param name="stat">The name of the stat to chart.</param> /// <param name="period">The period to use for the chart.</param> /// <returns>A memory stream for the chart image.</returns> public async Task<MemoryStream> GetTimeSeriesMetricImage(string metricNamespace, string metric, string stat, int period) { var metricImageWidget = new { title = "Example Metric Graph", view = "timeSeries", stacked = false, period = period, width = 1400, height = 600, metrics = new List<List<object>> { new() { metricNamespace, metric, new { stat } } } }; var metricImageWidgetString = JsonSerializer.Serialize(metricImageWidget); var imageResponse = await _amazonCloudWatch.GetMetricWidgetImageAsync( new GetMetricWidgetImageRequest() { MetricWidget = metricImageWidgetString }); return imageResponse.MetricWidgetImage; Actions 3035 Amazon CloudWatch } User Guide /// <summary> /// Save a metric image to a file. /// </summary> /// <param name="memoryStream">The MemoryStream for the metric image.</param> /// <param name="metricName">The name of the metric.</param> /// <returns>The path to the file.</returns> public string SaveMetricImage(MemoryStream memoryStream, string metricName) { var
acw-ug-851
acw-ug.pdf
851
"Example Metric Graph", view = "timeSeries", stacked = false, period = period, width = 1400, height = 600, metrics = new List<List<object>> { new() { metricNamespace, metric, new { stat } } } }; var metricImageWidgetString = JsonSerializer.Serialize(metricImageWidget); var imageResponse = await _amazonCloudWatch.GetMetricWidgetImageAsync( new GetMetricWidgetImageRequest() { MetricWidget = metricImageWidgetString }); return imageResponse.MetricWidgetImage; Actions 3035 Amazon CloudWatch } User Guide /// <summary> /// Save a metric image to a file. /// </summary> /// <param name="memoryStream">The MemoryStream for the metric image.</param> /// <param name="metricName">The name of the metric.</param> /// <returns>The path to the file.</returns> public string SaveMetricImage(MemoryStream memoryStream, string metricName) { var metricFileName = $"{metricName}_{DateTime.Now.Ticks}.png"; using var sr = new StreamReader(memoryStream); // Writes the memory stream to a file. File.WriteAllBytes(metricFileName, memoryStream.ToArray()); var filePath = Path.Join(AppDomain.CurrentDomain.BaseDirectory, metricFileName); return filePath; } • For API details, see GetMetricWidgetImage in AWS SDK for .NET API Reference. CLI AWS CLI To retrieve a snapshot graph of CPUUtilization The following get-metric-widget-image example retrieves snapshot graph for the metric CPUUtilization of the EC2 instance with the ID i-abcde and saves the retrieved image as a file named "image.png" on your local machine. aws cloudwatch get-metric-widget-image \ --metric-widget '{"metrics":[["AWS/EC2","CPUUtilization","InstanceId","i- abcde"]]}' \ --output-format png \ --output text | base64 --decode > image.png This command produces no output. • For API details, see GetMetricWidgetImage in AWS CLI Command Reference. Actions 3036 Amazon CloudWatch Java SDK for Java 2.x Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Retrieves and saves a custom metric image to a file. * * @param fileName the name of the file to save the metric image to * @return a {@link CompletableFuture} that completes when the image has been saved to the file */ public CompletableFuture<Void> downloadAndSaveMetricImageAsync(String fileName) { logger.info("Getting Image data for custom metric."); String myJSON = """ { "title": "Example Metric Graph", "view": "timeSeries", "stacked ": false, "period": 10, "width": 1400, "height": 600, "metrics": [ [ "AWS/Billing", "EstimatedCharges", "Currency", "USD" ] ] } """; GetMetricWidgetImageRequest imageRequest = GetMetricWidgetImageRequest.builder() Actions 3037 Amazon CloudWatch User Guide .metricWidget(myJSON) .build(); return getAsyncClient().getMetricWidgetImage(imageRequest) .thenCompose(response -> { SdkBytes sdkBytes = response.metricWidgetImage(); byte[] bytes = sdkBytes.asByteArray(); return CompletableFuture.runAsync(() -> { try { File outputFile = new File(fileName); try (FileOutputStream outputStream = new FileOutputStream(outputFile)) { outputStream.write(bytes); } } catch (IOException e) { throw new RuntimeException("Failed to write image to file", e); } }); }) .whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error getting and saving metric image", exception); } else { logger.info("Image data saved successfully to {}", fileName); } }); } • For API details, see GetMetricWidgetImage in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 3038 Amazon CloudWatch User Guide suspend fun getAndOpenMetricImage(fileName: String) { println("Getting Image data for custom metric.") val myJSON = """{ "title": "Example Metric Graph", "view": "timeSeries", "stacked ": false, "period": 10, "width": 1400, "height": 600, "metrics": [ [ "AWS/Billing", "EstimatedCharges", "Currency", "USD" ] ] }""" val imageRequest = GetMetricWidgetImageRequest { metricWidget = myJSON } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricWidgetImage(imageRequest) val bytes = response.metricWidgetImage if (bytes != null) { File(fileName).writeBytes(bytes) } } println("You have successfully written data to $fileName") } • For API details, see GetMetricWidgetImage in AWS SDK for Kotlin API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 3039 Amazon CloudWatch User Guide Use ListDashboards with an AWS SDK or CLI The following code examples show how to use ListDashboards. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Get a list of dashboards. /// </summary> /// <returns>A list of DashboardEntry objects.</returns> public async Task<List<DashboardEntry>> ListDashboards() { var results = new List<DashboardEntry>(); var paginateDashboards = _amazonCloudWatch.Paginators.ListDashboards( new ListDashboardsRequest()); // Get the entire list using the paginator. await foreach (var data in paginateDashboards.DashboardEntries) { results.Add(data); } return results; } • For API details, see ListDashboards in AWS SDK for .NET API Reference. CLI AWS CLI To retrieve a list of Dashboards The following list-dashboards example lists all the Dashboards in the specified account. Actions 3040 Amazon CloudWatch User Guide aws cloudwatch list-dashboards Output: { "DashboardEntries": [ { "DashboardName": "Dashboard-A", "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/ Dashboard-A", "LastModified": "2024-10-11T18:40:11+00:00", "Size": 271 }, { "DashboardName": "Dashboard-B", "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/ Dashboard-B", "LastModified": "2024-10-11T18:44:41+00:00", "Size": 522 } ] } For more information, see Amazon CloudWatch dashboards in the Amazon CloudWatch User Guide. • For API details, see ListDashboards in AWS CLI
acw-ug-852
acw-ug.pdf
852
paginateDashboards.DashboardEntries) { results.Add(data); } return results; } • For API details, see ListDashboards in AWS SDK for .NET API Reference. CLI AWS CLI To retrieve a list of Dashboards The following list-dashboards example lists all the Dashboards in the specified account. Actions 3040 Amazon CloudWatch User Guide aws cloudwatch list-dashboards Output: { "DashboardEntries": [ { "DashboardName": "Dashboard-A", "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/ Dashboard-A", "LastModified": "2024-10-11T18:40:11+00:00", "Size": 271 }, { "DashboardName": "Dashboard-B", "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/ Dashboard-B", "LastModified": "2024-10-11T18:44:41+00:00", "Size": 522 } ] } For more information, see Amazon CloudWatch dashboards in the Amazon CloudWatch User Guide. • For API details, see ListDashboards in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Lists the available dashboards. Actions 3041 Amazon CloudWatch * User Guide * @return a {@link CompletableFuture} that completes when the operation is finished. * The future will complete exceptionally if an error occurs while listing the dashboards. */ public CompletableFuture<Void> listDashboardsAsync() { ListDashboardsRequest listDashboardsRequest = ListDashboardsRequest.builder().build(); ListDashboardsPublisher paginator = getAsyncClient().listDashboardsPaginator(listDashboardsRequest); return paginator.subscribe(response -> { response.dashboardEntries().forEach(entry -> { logger.info("Dashboard name is: {} ", entry.dashboardName()); logger.info("Dashboard ARN is: {} ", entry.dashboardArn()); }); }).exceptionally(ex -> { logger.info("Failed to list dashboards: {} ", ex.getMessage()); throw new RuntimeException("Error occurred while listing dashboards", ex); }); } • For API details, see ListDashboards in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun listDashboards() { CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient .listDashboardsPaginated({}) .transform { it.dashboardEntries?.forEach { obj -> emit(obj) } } .collect { obj -> Actions 3042 Amazon CloudWatch User Guide println("Name is ${obj.dashboardName}") println("Dashboard ARN is ${obj.dashboardArn}") } } } • For API details, see ListDashboards in AWS SDK for Kotlin API reference. PowerShell Tools for PowerShell Example 1: Returns the collection of dashboards for your account. Get-CWDashboardList Output: DashboardArn DashboardName LastModified Size ------------ ------------- ------------ ---- arn:... Dashboard1 7/6/2017 8:14:15 PM 252 Example 2: Returns the collection of dashboards for your account whose names start with the prefix 'dev'. Get-CWDashboardList -DashboardNamePrefix dev • For API details, see ListDashboards in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ListMetrics with an AWS SDK or CLI The following code examples show how to use ListMetrics. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: Actions 3043 Amazon CloudWatch • Learn the basics • Manage metrics and alarms .NET SDK for .NET Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// List metrics available, optionally within a namespace. /// </summary> /// <param name="metricNamespace">Optional CloudWatch namespace to use when listing metrics.</param> /// <param name="filter">Optional dimension filter.</param> /// <param name="metricName">Optional metric name filter.</param> /// <returns>The list of metrics.</returns> public async Task<List<Metric>> ListMetrics(string? metricNamespace = null, DimensionFilter? filter = null, string? metricName = null) { var results = new List<Metric>(); var paginateMetrics = _amazonCloudWatch.Paginators.ListMetrics( new ListMetricsRequest { Namespace = metricNamespace, Dimensions = filter != null ? new List<DimensionFilter> { filter } : null, MetricName = metricName }); // Get the entire list using the paginator. await foreach (var metric in paginateMetrics.Metrics) { results.Add(metric); } return results; } Actions 3044 Amazon CloudWatch User Guide • For API details, see ListMetrics in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Include the required files. #include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/ListMetricsRequest.h> #include <aws/monitoring/model/ListMetricsResult.h> #include <iomanip> #include <iostream> List the metrics. Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::ListMetricsRequest request; if (argc > 1) { request.SetMetricName(argv[1]); } if (argc > 2) { request.SetNamespace(argv[2]); } bool done = false; bool header = false; Actions 3045 Amazon CloudWatch User Guide while (!done) { auto outcome = cw.ListMetrics(request); if (!outcome.IsSuccess()) { std::cout << "Failed to list CloudWatch metrics:" << outcome.GetError().GetMessage() << std::endl; break; } if (!header) { std::cout << std::left << std::setw(48) << "MetricName" << std::setw(32) << "Namespace" << "DimensionNameValuePairs" << std::endl; header = true; } const auto &metrics = outcome.GetResult().GetMetrics(); for (const auto &metric : metrics) { std::cout << std::left << std::setw(48) << metric.GetMetricName() << std::setw(32) << metric.GetNamespace(); const auto &dimensions = metric.GetDimensions(); for (auto iter = dimensions.cbegin(); iter != dimensions.cend(); ++iter) { const auto &dimkv = *iter; std::cout << dimkv.GetName() << " = " <<
acw-ug-853
acw-ug.pdf
853
Amazon CloudWatch User Guide while (!done) { auto outcome = cw.ListMetrics(request); if (!outcome.IsSuccess()) { std::cout << "Failed to list CloudWatch metrics:" << outcome.GetError().GetMessage() << std::endl; break; } if (!header) { std::cout << std::left << std::setw(48) << "MetricName" << std::setw(32) << "Namespace" << "DimensionNameValuePairs" << std::endl; header = true; } const auto &metrics = outcome.GetResult().GetMetrics(); for (const auto &metric : metrics) { std::cout << std::left << std::setw(48) << metric.GetMetricName() << std::setw(32) << metric.GetNamespace(); const auto &dimensions = metric.GetDimensions(); for (auto iter = dimensions.cbegin(); iter != dimensions.cend(); ++iter) { const auto &dimkv = *iter; std::cout << dimkv.GetName() << " = " << dimkv.GetValue(); if (iter + 1 != dimensions.cend()) { std::cout << ", "; } } std::cout << std::endl; } const auto &next_token = outcome.GetResult().GetNextToken(); request.SetNextToken(next_token); done = next_token.empty(); } Actions 3046 Amazon CloudWatch User Guide • For API details, see ListMetrics in AWS SDK for C++ API Reference. CLI AWS CLI To list the metrics for Amazon SNS The following list-metrics example displays the metrics for Amazon SNS. aws cloudwatch list-metrics \ --namespace "AWS/SNS" Output: { "Metrics": [ { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "NotifyMe" } ], "MetricName": "PublishSize" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "CFO" } ], "MetricName": "PublishSize" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "NotifyMe" Actions 3047 Amazon CloudWatch } ], "MetricName": "NumberOfNotificationsFailed" User Guide }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "NotifyMe" } ], "MetricName": "NumberOfNotificationsDelivered" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "NotifyMe" } ], "MetricName": "NumberOfMessagesPublished" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "CFO" } ], "MetricName": "NumberOfMessagesPublished" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "CFO" } ], "MetricName": "NumberOfNotificationsDelivered" }, Actions 3048 Amazon CloudWatch { User Guide "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "CFO" } ], "MetricName": "NumberOfNotificationsFailed" } ] } • For API details, see ListMetrics in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Retrieves a list of metric names for the specified namespace. * * @param namespace the namespace for which to retrieve the metric names * @return a {@link CompletableFuture} that, when completed, contains an {@link ArrayList} of * the metric names in the specified namespace * @throws RuntimeException if an error occurs while listing the metrics */ public CompletableFuture<ArrayList<String>> listMetsAsync(String namespace) { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .build(); ListMetricsPublisher metricsPaginator = getAsyncClient().listMetricsPaginator(request); Set<String> metSet = new HashSet<>(); Actions 3049 Amazon CloudWatch User Guide CompletableFuture<Void> future = metricsPaginator.subscribe(response -> { response.metrics().forEach(metric -> { String metricName = metric.metricName(); metSet.add(metricName); }); }); return future .thenApply(ignored -> new ArrayList<>(metSet)) .exceptionally(exception -> { throw new RuntimeException("Failed to list metrics: " + exception.getMessage(), exception); }); } • For API details, see ListMetrics in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Import the SDK and client modules and call the API. import { CloudWatchServiceException, ListMetricsCommand, } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; export const main = async () => { // 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({ Actions 3050 Amazon CloudWatch User Guide Dimensions: [ { Name: "LogGroupName", }, ], MetricName: "IncomingLogEvents", Namespace: "AWS/Logs", }); try { const response = await client.send(command); console.log(`Metrics count: ${response.Metrics?.length}`); return response; } catch (caught) { if (caught instanceof CloudWatchServiceException) { console.error(`Error from CloudWatch. ${caught.name}: ${caught.message}`); } else { throw caught; } } }; Create the client in a separate module and export it. import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({}); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see ListMetrics in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. // Load the AWS SDK for Node.js Actions 3051 Amazon CloudWatch User Guide 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)); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see ListMetrics in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more
acw-ug-854
acw-ug.pdf
854
for Node.js Actions 3051 Amazon CloudWatch User Guide 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)); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see ListMetrics in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun listMets(namespaceVal: String?): ArrayList<String>? { val metList = ArrayList<String>() Actions 3052 Amazon CloudWatch User Guide val request = ListMetricsRequest { namespace = namespaceVal } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val reponse = cwClient.listMetrics(request) reponse.metrics?.forEach { metrics -> val data = metrics.metricName if (!metList.contains(data)) { metList.add(data!!) } } } return metList } • For API details, see ListMetrics in AWS SDK for Kotlin API reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def list_metrics(self, namespace, name, recent=False): """ Gets the metrics within a namespace that have the specified name. Actions 3053 Amazon CloudWatch User Guide If the metric has no dimensions, a single metric is returned. Otherwise, metrics for all dimensions are returned. :param namespace: The namespace of the metric. :param name: The name of the metric. :param recent: When True, only metrics that have been active in the last three hours are returned. :return: An iterator that yields the retrieved metrics. """ try: kwargs = {"Namespace": namespace, "MetricName": name} if recent: kwargs["RecentlyActive"] = "PT3H" # List past 3 hours only metric_iter = self.cloudwatch_resource.metrics.filter(**kwargs) logger.info("Got metrics for %s.%s.", namespace, name) except ClientError: logger.exception("Couldn't get metrics for %s.%s.", namespace, name) raise else: return metric_iter • For API details, see ListMetrics in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. # Lists available metrics for a metric namespace in Amazon CloudWatch. # # @param cloudwatch_client [Aws::CloudWatch::Client] # An initialized CloudWatch client. # @param metric_namespace [String] The namespace of the metric. # @example # list_metrics_for_namespace( Actions 3054 Amazon CloudWatch User Guide # Aws::CloudWatch::Client.new(region: 'us-east-1'), # 'SITE/TRAFFIC' # ) def list_metrics_for_namespace(cloudwatch_client, metric_namespace) response = cloudwatch_client.list_metrics(namespace: metric_namespace) if response.metrics.count.positive? response.metrics.each do |metric| puts " Metric name: #{metric.metric_name}" if metric.dimensions.count.positive? puts ' Dimensions:' metric.dimensions.each do |dimension| puts " Name: #{dimension.name}, Value: #{dimension.value}" end else puts 'No dimensions found.' end end else puts "No metrics found for namespace '#{metric_namespace}'. " \ 'Note that it could take up to 15 minutes for recently-added metrics ' \ 'to become available.' end end # Example usage: def run_me metric_namespace = 'SITE/TRAFFIC' # Replace us-west-2 with the AWS Region you're using for Amazon CloudWatch. region = 'us-east-1' cloudwatch_client = Aws::CloudWatch::Client.new(region: region) # Add three datapoints. puts 'Continuing...' unless datapoint_added_to_metric?( cloudwatch_client, metric_namespace, 'UniqueVisitors', 'SiteName', 'example.com', 5_885.0, 'Count' ) Actions 3055 Amazon CloudWatch User Guide puts 'Continuing...' unless datapoint_added_to_metric?( cloudwatch_client, metric_namespace, 'UniqueVisits', 'SiteName', 'example.com', 8_628.0, 'Count' ) puts 'Continuing...' unless datapoint_added_to_metric?( cloudwatch_client, metric_namespace, 'PageViews', 'PageURL', 'example.html', 18_057.0, 'Count' ) puts "Metrics for namespace '#{metric_namespace}':" list_metrics_for_namespace(cloudwatch_client, metric_namespace) end run_me if $PROGRAM_NAME == __FILE__ • For API details, see ListMetrics in AWS SDK for Ruby API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. "The following list-metrics example displays the metrics for Amazon CloudWatch." TRY. Actions 3056 Amazon CloudWatch User Guide oo_result = lo_cwt->listmetrics( " oo_result is returned for testing purposes. " iv_namespace = iv_namespace ). DATA(lt_metrics) = oo_result->get_metrics( ). MESSAGE 'Metrics retrieved.' TYPE 'I'. CATCH /aws1/cx_cwtinvparamvalueex. MESSAGE 'The specified argument was not valid.' TYPE 'E'. ENDTRY. • For API details, see ListMetrics in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use PutAnomalyDetector with an AWS SDK or CLI The following code examples show how to use PutAnomalyDetector. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics .NET SDK for .NET Note There's more on GitHub. Find the
acw-ug-855
acw-ug.pdf
855
ListMetrics in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use PutAnomalyDetector with an AWS SDK or CLI The following code examples show how to use PutAnomalyDetector. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Add an anomaly detector for a single metric. /// </summary> /// <param name="anomalyDetector">A single metric anomaly detector.</param> /// <returns>True if successful.</returns> Actions 3057 Amazon CloudWatch User Guide public async Task<bool> PutAnomalyDetector(SingleMetricAnomalyDetector anomalyDetector) { var putAlarmDetectorResult = await _amazonCloudWatch.PutAnomalyDetectorAsync( new PutAnomalyDetectorRequest() { SingleMetricAnomalyDetector = anomalyDetector }); return putAlarmDetectorResult.HttpStatusCode == HttpStatusCode.OK; } • For API details, see PutAnomalyDetector in AWS SDK for .NET API Reference. CLI AWS CLI To create an anomaly detection model The following put-anomaly-detector example creates an anomaly detection model for a CloudWatch metric. aws cloudwatch put-anomaly-detector \ --namespace AWS/Logs \ --metric-name IncomingBytes \ --stat SampleCount This command produces no output. For more information, see Using CloudWatch anomaly detection in the Amazon CloudWatch User Guide. • For API details, see PutAnomalyDetector in AWS CLI Command Reference. Actions 3058 Amazon CloudWatch Java SDK for Java 2.x Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Adds an anomaly detector for the given file. * * @param fileName the name of the file containing the anomaly detector configuration * @return a {@link CompletableFuture} that completes when the anomaly detector has been added */ public CompletableFuture<Void> addAnomalyDetectorAsync(String fileName) { CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); return new ObjectMapper().readTree(parser); // Return the root node } catch (IOException e) { throw new RuntimeException("Failed to read or parse the file", e); } }); return readFileFuture.thenCompose(rootNode -> { try { String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder() Actions 3059 Amazon CloudWatch User Guide .metricName(customMetricName) .namespace(customMetricNamespace) .stat("Maximum") .build(); PutAnomalyDetectorRequest anomalyDetectorRequest = PutAnomalyDetectorRequest.builder() .singleMetricAnomalyDetector(singleMetricAnomalyDetector) .build(); return getAsyncClient().putAnomalyDetector(anomalyDetectorRequest).thenAccept(response -> { logger.info("Added anomaly detector for metric {}", customMetricName); }); } catch (Exception e) { throw new RuntimeException("Failed to create anomaly detector", e); } }).whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error adding anomaly detector", exception); } }); } • For API details, see PutAnomalyDetector in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun addAnomalyDetector(fileName: String?) { Actions 3060 Amazon CloudWatch User Guide // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() val singleMetricAnomalyDetectorVal = SingleMetricAnomalyDetector { metricName = customMetricName namespace = customMetricNamespace stat = "Maximum" } val anomalyDetectorRequest = PutAnomalyDetectorRequest { singleMetricAnomalyDetector = singleMetricAnomalyDetectorVal } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putAnomalyDetector(anomalyDetectorRequest) println("Added anomaly detector for metric $customMetricName.") } } • For API details, see PutAnomalyDetector in AWS SDK for Kotlin API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use PutDashboard with an AWS SDK or CLI The following code examples show how to use PutDashboard. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics Actions 3061 Amazon CloudWatch .NET SDK for .NET Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Set up a dashboard using a call to the wrapper class. /// </summary> /// <param name="customMetricNamespace">The metric namespace.</param> /// <param name="customMetricName">The metric name.</param> /// <param name="dashboardName">The name of the dashboard.</param> /// <returns>A list of validation messages.</returns> private static async Task<List<DashboardValidationMessage>> SetupDashboard( string customMetricNamespace, string customMetricName, string dashboardName) { // Get the dashboard model from configuration. var newDashboard = new DashboardModel(); _configuration.GetSection("dashboardExampleBody").Bind(newDashboard); // Add a new metric to the dashboard. newDashboard.Widgets.Add(new Widget { Height = 8, Width = 8, Y = 8, X = 0, Type = "metric", Properties = new Properties { Metrics = new List<List<object>> { new() { customMetricNamespace, customMetricName } }, View = "timeSeries", Region = "us-east-1", Stat = "Sum",
acw-ug-856
acw-ug.pdf
856
</summary> /// <param name="customMetricNamespace">The metric namespace.</param> /// <param name="customMetricName">The metric name.</param> /// <param name="dashboardName">The name of the dashboard.</param> /// <returns>A list of validation messages.</returns> private static async Task<List<DashboardValidationMessage>> SetupDashboard( string customMetricNamespace, string customMetricName, string dashboardName) { // Get the dashboard model from configuration. var newDashboard = new DashboardModel(); _configuration.GetSection("dashboardExampleBody").Bind(newDashboard); // Add a new metric to the dashboard. newDashboard.Widgets.Add(new Widget { Height = 8, Width = 8, Y = 8, X = 0, Type = "metric", Properties = new Properties { Metrics = new List<List<object>> { new() { customMetricNamespace, customMetricName } }, View = "timeSeries", Region = "us-east-1", Stat = "Sum", Period = 86400, Actions 3062 Amazon CloudWatch User Guide YAxis = new YAxis { Left = new Left { Min = 0, Max = 100 } }, Title = "Custom Metric Widget", LiveData = true, Sparkline = true, Trend = true, Stacked = false, SetPeriodToTimeRange = false } }); var newDashboardString = JsonSerializer.Serialize(newDashboard, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }); var validationMessages = await _cloudWatchWrapper.PutDashboard(dashboardName, newDashboardString); return validationMessages; } /// <summary> /// Wrapper to create or add to a dashboard with metrics. /// </summary> /// <param name="dashboardName">The name for the dashboard.</param> /// <param name="dashboardBody">The metric data in JSON for the dashboard.</ param> /// <returns>A list of validation messages for the dashboard.</returns> public async Task<List<DashboardValidationMessage>> PutDashboard(string dashboardName, string dashboardBody) { // Updating a dashboard replaces all contents. // Best practice is to include a text widget indicating this dashboard was created programmatically. var dashboardResponse = await _amazonCloudWatch.PutDashboardAsync( new PutDashboardRequest() { DashboardName = dashboardName, DashboardBody = dashboardBody }); return dashboardResponse.DashboardValidationMessages; } Actions 3063 Amazon CloudWatch User Guide • For API details, see PutDashboard in AWS SDK for .NET API Reference. CLI AWS CLI To create a dashboard The following put-dashboard example creates a dashboard named Dashboard-A in the specified account. aws cloudwatch put-dashboard \ --dashboard-name Dashboard-A \ --dashboard-body '{"widgets": [{"height":6,"width":6,"y":0,"x":0,"type":"metric","properties": {"view":"timeSeries","stacked":false,"metrics": [["Namespace","CPUUtilization","Environment","Prod","Type","App"]],"region":"us- east-1"}}]}' Output: { "DashboardValidationMessages": [] } For more information, see Creating a CloudWatch dashboard in the Amazon CloudWatch User Guide. • For API details, see PutDashboard in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 3064 Amazon CloudWatch User Guide /** * Creates a new dashboard with the specified name and metrics from the given file. * * @param dashboardName the name of the dashboard to be created * @param fileName the name of the file containing the dashboard body * @return a {@link CompletableFuture} representing the asynchronous operation of creating the dashboard * @throws IOException if there is an error reading the dashboard body from the file */ public CompletableFuture<PutDashboardResponse> createDashboardWithMetricsAsync(String dashboardName, String fileName) throws IOException { String dashboardBody = readFileAsString(fileName); PutDashboardRequest dashboardRequest = PutDashboardRequest.builder() .dashboardName(dashboardName) .dashboardBody(dashboardBody) .build(); return getAsyncClient().putDashboard(dashboardRequest) .handle((response, ex) -> { if (ex != null) { logger.info("Failed to create dashboard: {}", ex.getMessage()); throw new RuntimeException("Dashboard creation failed", ex); } else { // Handle the normal response case logger.info("{} was successfully created.", dashboardName); List<DashboardValidationMessage> messages = response.dashboardValidationMessages(); if (messages.isEmpty()) { logger.info("There are no messages in the new Dashboard."); } else { for (DashboardValidationMessage message : messages) { logger.info("Message: {}", message.message()); } } return response; // Return the response for further use } }); Actions 3065 Amazon CloudWatch } User Guide • For API details, see PutDashboard in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun createDashboardWithMetrics( dashboardNameVal: String, fileNameVal: String, ) { val dashboardRequest = PutDashboardRequest { dashboardName = dashboardNameVal dashboardBody = readFileAsString(fileNameVal) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.putDashboard(dashboardRequest) println("$dashboardNameVal was successfully created.") val messages = response.dashboardValidationMessages if (messages != null) { if (messages.isEmpty()) { println("There are no messages in the new Dashboard") } else { for (message in messages) { println("Message is: ${message.message}") } } } } } Actions 3066 Amazon CloudWatch User Guide • For API details, see PutDashboard in AWS SDK for Kotlin API reference. PowerShell Tools for PowerShell Example 1: Creates or updates the dashboard named 'Dashboard1' to include two metric widgets side by side. $dashBody = @" { "widgets":[ { "type":"metric", "x":0, "y":0, "width":12, "height":6, "properties":{ "metrics":[ [ "AWS/EC2", "CPUUtilization", "InstanceId", "i-012345" ] ], "period":300, "stat":"Average", "region":"us-east-1", "title":"EC2 Instance CPU" } }, { "type":"metric", "x":12, "y":0, "width":12, "height":6, "properties":{ "metrics":[ [ "AWS/S3", Actions 3067 Amazon CloudWatch User Guide "BucketSizeBytes", "BucketName", "amzn-s3-demo-bucket" ] ], "period":86400, "stat":"Maximum", "region":"us-east-1", "title":"amzn-s3-demo-bucket bytes" } } ] } "@ Write-CWDashboard -DashboardName Dashboard1 -DashboardBody $dashBody Example 2: Creates or updates the dashboard, piping the content describing the dashboard into the cmdlet. $dashBody = @" { ... } "@ $dashBody | Write-CWDashboard -DashboardName Dashboard1 • For API details, see
acw-ug-857
acw-ug.pdf
857
side by side. $dashBody = @" { "widgets":[ { "type":"metric", "x":0, "y":0, "width":12, "height":6, "properties":{ "metrics":[ [ "AWS/EC2", "CPUUtilization", "InstanceId", "i-012345" ] ], "period":300, "stat":"Average", "region":"us-east-1", "title":"EC2 Instance CPU" } }, { "type":"metric", "x":12, "y":0, "width":12, "height":6, "properties":{ "metrics":[ [ "AWS/S3", Actions 3067 Amazon CloudWatch User Guide "BucketSizeBytes", "BucketName", "amzn-s3-demo-bucket" ] ], "period":86400, "stat":"Maximum", "region":"us-east-1", "title":"amzn-s3-demo-bucket bytes" } } ] } "@ Write-CWDashboard -DashboardName Dashboard1 -DashboardBody $dashBody Example 2: Creates or updates the dashboard, piping the content describing the dashboard into the cmdlet. $dashBody = @" { ... } "@ $dashBody | Write-CWDashboard -DashboardName Dashboard1 • For API details, see PutDashboard in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use PutMetricAlarm with an AWS SDK or CLI The following code examples show how to use PutMetricAlarm. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Learn the basics Actions 3068 Amazon CloudWatch • Get started with alarms • Manage metrics and alarms .NET SDK for .NET Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Add a metric alarm to send an email when the metric passes a threshold. /// </summary> /// <param name="alarmDescription">A description of the alarm.</param> /// <param name="alarmName">The name for the alarm.</param> /// <param name="comparison">The type of comparison to use.</param> /// <param name="metricName">The name of the metric for the alarm.</param> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="threshold">The threshold value for the alarm.</param> /// <param name="alarmActions">Optional actions to execute when in an alarm state.</param> /// <returns>True if successful.</returns> public async Task<bool> PutMetricEmailAlarm(string alarmDescription, string alarmName, ComparisonOperator comparison, string metricName, string metricNamespace, double threshold, List<string> alarmActions = null!) { try { var putEmailAlarmResponse = await _amazonCloudWatch.PutMetricAlarmAsync( new PutMetricAlarmRequest() { AlarmActions = alarmActions, AlarmDescription = alarmDescription, AlarmName = alarmName, ComparisonOperator = comparison, Threshold = threshold, Actions 3069 Amazon CloudWatch User Guide Namespace = metricNamespace, MetricName = metricName, EvaluationPeriods = 1, Period = 10, Statistic = new Statistic("Maximum"), DatapointsToAlarm = 1, TreatMissingData = "ignore" }); return putEmailAlarmResponse.HttpStatusCode == HttpStatusCode.OK; } catch (LimitExceededException lex) { _logger.LogError(lex, $"Unable to add alarm {alarmName}. Alarm quota has already been reached."); } return false; } /// <summary> /// Add specific email actions to a list of action strings for a CloudWatch alarm. /// </summary> /// <param name="accountId">The AccountId for the alarm.</param> /// <param name="region">The region for the alarm.</param> /// <param name="emailTopicName">An Amazon Simple Notification Service (SNS) topic for the alarm email.</param> /// <param name="alarmActions">Optional list of existing alarm actions to append to.</param> /// <returns>A list of string actions for an alarm.</returns> public List<string> AddEmailAlarmAction(string accountId, string region, string emailTopicName, List<string>? alarmActions = null) { alarmActions ??= new List<string>(); var snsAlarmAction = $"arn:aws:sns:{region}:{accountId}: {emailTopicName}"; alarmActions.Add(snsAlarmAction); return alarmActions; } • For API details, see PutMetricAlarm in AWS SDK for .NET API Reference. Actions 3070 Amazon CloudWatch C++ SDK for C++ Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Include the required files. #include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/PutMetricAlarmRequest.h> #include <iostream> Create the alarm to watch the metric. Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::PutMetricAlarmRequest request; request.SetAlarmName(alarm_name); request.SetComparisonOperator( Aws::CloudWatch::Model::ComparisonOperator::GreaterThanThreshold); request.SetEvaluationPeriods(1); request.SetMetricName("CPUUtilization"); request.SetNamespace("AWS/EC2"); request.SetPeriod(60); request.SetStatistic(Aws::CloudWatch::Model::Statistic::Average); request.SetThreshold(70.0); request.SetActionsEnabled(false); request.SetAlarmDescription("Alarm when server CPU exceeds 70%"); request.SetUnit(Aws::CloudWatch::Model::StandardUnit::Seconds); Aws::CloudWatch::Model::Dimension dimension; dimension.SetName("InstanceId"); dimension.SetValue(instanceId); request.AddDimensions(dimension); auto outcome = cw.PutMetricAlarm(request); Actions 3071 Amazon CloudWatch User Guide if (!outcome.IsSuccess()) { std::cout << "Failed to create CloudWatch alarm:" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully created CloudWatch alarm " << alarm_name << std::endl; } • For API details, see PutMetricAlarm in AWS SDK for C++ API Reference. CLI AWS CLI To send an Amazon Simple Notification Service email message when CPU utilization exceeds 70 percent The following example uses the put-metric-alarm command to send an Amazon Simple Notification Service email message when CPU utilization exceeds 70 percent: aws cloudwatch put-metric-alarm --alarm-name cpu-mon --alarm-description "Alarm when CPU exceeds 70 percent" --metric-name CPUUtilization --namespace AWS/ EC2 --statistic Average --period 300 --threshold 70 --comparison- operator GreaterThanThreshold --dimensions "Name=InstanceId,Value=i-12345678" -- evaluation-periods 2 --alarm-actions arn:aws:sns:us-east-1:111122223333:MyTopic --unit Percent This command returns to the prompt if successful. If an alarm with the same name already exists, it will be overwritten by the new alarm. To specify multiple dimensions The following example illustrates how to specify multiple dimensions. Each dimension is specified as a Name/Value pair, with a comma between the name and the value. Multiple dimensions are separated by a space: aws cloudwatch put-metric-alarm --alarm-name "Default_Test_Alarm3" --alarm- description "The default example alarm" --namespace "CW EXAMPLE METRICS" Actions 3072
acw-ug-858
acw-ug.pdf
858
--namespace AWS/ EC2 --statistic Average --period 300 --threshold 70 --comparison- operator GreaterThanThreshold --dimensions "Name=InstanceId,Value=i-12345678" -- evaluation-periods 2 --alarm-actions arn:aws:sns:us-east-1:111122223333:MyTopic --unit Percent This command returns to the prompt if successful. If an alarm with the same name already exists, it will be overwritten by the new alarm. To specify multiple dimensions The following example illustrates how to specify multiple dimensions. Each dimension is specified as a Name/Value pair, with a comma between the name and the value. Multiple dimensions are separated by a space: aws cloudwatch put-metric-alarm --alarm-name "Default_Test_Alarm3" --alarm- description "The default example alarm" --namespace "CW EXAMPLE METRICS" Actions 3072 Amazon CloudWatch User Guide --metric-name Default_Test --statistic Average --period 60 --evaluation- periods 3 --threshold 50 --comparison-operator GreaterThanOrEqualToThreshold -- dimensions Name=key1,Value=value1 Name=key2,Value=value2 • For API details, see PutMetricAlarm in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Creates an alarm based on the configuration provided in a JSON file. * * @param fileName the name of the JSON file containing the alarm configuration * @return a CompletableFuture that represents the asynchronous operation of creating the alarm * @throws RuntimeException if an exception occurs while reading the JSON file or creating the alarm */ public CompletableFuture<String> createAlarmAsync(String fileName) { com.fasterxml.jackson.databind.JsonNode rootNode; try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); rootNode = new ObjectMapper().readTree(parser); } catch (IOException e) { throw new RuntimeException("Failed to read the alarm configuration file", e); } // Extract values from the JSON node. String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); Actions 3073 Amazon CloudWatch User Guide String alarmName = rootNode.findValue("exampleAlarmName").asText(); String emailTopic = rootNode.findValue("emailTopic").asText(); String accountId = rootNode.findValue("accountId").asText(); String region = rootNode.findValue("region").asText(); // Create a List for alarm actions. List<String> alarmActions = new ArrayList<>(); alarmActions.add("arn:aws:sns:" + region + ":" + accountId + ":" + emailTopic); PutMetricAlarmRequest alarmRequest = PutMetricAlarmRequest.builder() .alarmActions(alarmActions) .alarmDescription("Example metric alarm") .alarmName(alarmName) .comparisonOperator(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD) .threshold(100.00) .metricName(customMetricName) .namespace(customMetricNamespace) .evaluationPeriods(1) .period(10) .statistic("Maximum") .datapointsToAlarm(1) .treatMissingData("ignore") .build(); // Call the putMetricAlarm asynchronously and handle the result. return getAsyncClient().putMetricAlarm(alarmRequest) .handle((response, ex) -> { if (ex != null) { logger.info("Failed to create alarm: {}", ex.getMessage()); throw new RuntimeException("Failed to create alarm", ex); } else { logger.info("{} was successfully created!", alarmName); return alarmName; } }); } • For API details, see PutMetricAlarm in AWS SDK for Java 2.x API Reference. Actions 3074 Amazon CloudWatch JavaScript SDK for JavaScript (v3) Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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); Actions 3075 Amazon CloudWatch } }; export default run(); User Guide Create the client in a separate module and export it. import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({}); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see PutMetricAlarm in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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, Actions 3076 Amazon CloudWatch User Guide 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); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see PutMetricAlarm in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun putMetricAlarm( alarmNameVal: String, instanceIdVal: String, ) { val dimensionOb = Dimension { name = "InstanceId" value = instanceIdVal } Actions 3077
acw-ug-859
acw-ug.pdf
859
Name: "InstanceId", Value: "INSTANCE_ID", }, ], Unit: "Percent", }; cw.putMetricAlarm(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see PutMetricAlarm in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun putMetricAlarm( alarmNameVal: String, instanceIdVal: String, ) { val dimensionOb = Dimension { name = "InstanceId" value = instanceIdVal } Actions 3077 Amazon CloudWatch User Guide val request = PutMetricAlarmRequest { alarmName = alarmNameVal comparisonOperator = ComparisonOperator.GreaterThanThreshold evaluationPeriods = 1 metricName = "CPUUtilization" namespace = "AWS/EC2" period = 60 statistic = Statistic.fromValue("Average") threshold = 70.0 actionsEnabled = false alarmDescription = "An Alarm created by the Kotlin SDK when server CPU utilization exceeds 70%" unit = StandardUnit.fromValue("Seconds") dimensions = listOf(dimensionOb) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putMetricAlarm(request) println("Successfully created an alarm with name $alarmNameVal") } } • For API details, see PutMetricAlarm in AWS SDK for Kotlin API reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ Actions 3078 Amazon CloudWatch User Guide :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def create_metric_alarm( self, metric_namespace, metric_name, alarm_name, stat_type, period, eval_periods, threshold, comparison_op, ): """ Creates an alarm that watches a metric. :param metric_namespace: The namespace of the metric. :param metric_name: The name of the metric. :param alarm_name: The name of the alarm. :param stat_type: The type of statistic the alarm watches. :param period: The period in which metric data are grouped to calculate statistics. :param eval_periods: The number of periods that the metric must be over the alarm threshold before the alarm is set into an alarmed state. :param threshold: The threshold value to compare against the metric statistic. :param comparison_op: The comparison operation used to compare the threshold against the metric. :return: The newly created alarm. """ try: metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name) alarm = metric.put_alarm( AlarmName=alarm_name, Statistic=stat_type, Period=period, Actions 3079 Amazon CloudWatch User Guide EvaluationPeriods=eval_periods, Threshold=threshold, ComparisonOperator=comparison_op, ) logger.info( "Added alarm %s to track metric %s.%s.", alarm_name, metric_namespace, metric_name, ) except ClientError: logger.exception( "Couldn't add alarm %s to metric %s.%s", alarm_name, metric_namespace, metric_name, ) raise else: return alarm • For API details, see PutMetricAlarm in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. # Creates or updates an alarm in Amazon CloudWatch. # # @param cloudwatch_client [Aws::CloudWatch::Client] # An initialized CloudWatch client. # @param alarm_name [String] The name of the alarm. # @param alarm_description [String] A description about the alarm. # @param metric_name [String] The name of the metric associated with the alarm. Actions 3080 Amazon CloudWatch User Guide # @param alarm_actions [Array] A list of Strings representing the # Amazon Resource Names (ARNs) to execute when the alarm transitions to the # ALARM state. # @param namespace [String] The namespace for the metric to alarm on. # @param statistic [String] The statistic for the metric. # @param dimensions [Array] A list of dimensions for the metric, specified as # Aws::CloudWatch::Types::Dimension. # @param period [Integer] The number of seconds before re-evaluating the metric. # @param unit [String] The unit of measure for the statistic. # @param evaluation_periods [Integer] The number of periods over which data is # compared to the specified threshold. # @param theshold [Float] The value against which the specified statistic is compared. # @param comparison_operator [String] The arithmetic operation to use when # comparing the specified statistic and threshold. # @return [Boolean] true if the alarm was created or updated; otherwise, false. # @example # exit 1 unless alarm_created_or_updated?( # Aws::CloudWatch::Client.new(region: 'us-east-1'), # 'ObjectsInBucket', # 'Objects exist in this bucket for more than 1 day.', # 'NumberOfObjects', # ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic'], # 'AWS/S3', # 'Average', # [ # { # name: 'BucketName', # value: 'amzn-s3-demo-bucket' # }, # { # name: 'StorageType', # value: 'AllStorageTypes' # } # ], # 86_400, # 'Count', # 1, # 1, # 'GreaterThanThreshold' # ) def alarm_created_or_updated?( cloudwatch_client, alarm_name, Actions 3081 Amazon CloudWatch User Guide alarm_description, metric_name, alarm_actions, namespace, statistic, dimensions, period, unit, evaluation_periods, threshold, comparison_operator ) cloudwatch_client.put_metric_alarm( alarm_name: alarm_name, alarm_description: alarm_description, metric_name: metric_name, alarm_actions: alarm_actions, namespace: namespace, statistic: statistic, dimensions: dimensions, period: period, unit: unit, evaluation_periods: evaluation_periods, threshold: threshold, comparison_operator: comparison_operator ) true rescue StandardError => e puts "Error creating alarm: #{e.message}" false end • For API details, see PutMetricAlarm in AWS SDK for Ruby API Reference. Actions 3082 Amazon CloudWatch SAP
acw-ug-860
acw-ug.pdf
860
# name: 'StorageType', # value: 'AllStorageTypes' # } # ], # 86_400, # 'Count', # 1, # 1, # 'GreaterThanThreshold' # ) def alarm_created_or_updated?( cloudwatch_client, alarm_name, Actions 3081 Amazon CloudWatch User Guide alarm_description, metric_name, alarm_actions, namespace, statistic, dimensions, period, unit, evaluation_periods, threshold, comparison_operator ) cloudwatch_client.put_metric_alarm( alarm_name: alarm_name, alarm_description: alarm_description, metric_name: metric_name, alarm_actions: alarm_actions, namespace: namespace, statistic: statistic, dimensions: dimensions, period: period, unit: unit, evaluation_periods: evaluation_periods, threshold: threshold, comparison_operator: comparison_operator ) true rescue StandardError => e puts "Error creating alarm: #{e.message}" false end • For API details, see PutMetricAlarm in AWS SDK for Ruby API Reference. Actions 3082 Amazon CloudWatch SAP ABAP SDK for SAP ABAP Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. lo_cwt->putmetricalarm( iv_alarmname = iv_alarm_name iv_comparisonoperator = iv_comparison_operator iv_evaluationperiods = iv_evaluation_periods iv_metricname = iv_metric_name iv_namespace = iv_namespace iv_statistic = iv_statistic iv_threshold = iv_threshold iv_actionsenabled = iv_actions_enabled iv_alarmdescription = iv_alarm_description iv_unit = iv_unit iv_period = iv_period it_dimensions = it_dimensions ). MESSAGE 'Alarm created.' TYPE 'I'. CATCH /aws1/cx_cwtlimitexceededfault. MESSAGE 'The request processing has exceeded the limit' TYPE 'E'. ENDTRY. • For API details, see PutMetricAlarm in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use PutMetricData with an AWS SDK or CLI The following code examples show how to use PutMetricData. Actions 3083 Amazon CloudWatch User Guide Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Learn the basics • Manage metrics and alarms .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Add some metric data using a call to a wrapper class. /// </summary> /// <param name="customMetricName">The metric name.</param> /// <param name="customMetricNamespace">The metric namespace.</param> /// <returns></returns> private static async Task<List<MetricDatum>> PutRandomMetricData(string customMetricName, string customMetricNamespace) { List<MetricDatum> customData = new List<MetricDatum>(); Random rnd = new Random(); // Add 10 random values up to 100, starting with a timestamp 15 minutes in the past. var utcNowMinus15 = DateTime.UtcNow.AddMinutes(-15); for (int i = 0; i < 10; i++) { var metricValue = rnd.Next(0, 100); customData.Add( new MetricDatum { MetricName = customMetricName, Value = metricValue, Actions 3084 Amazon CloudWatch User Guide TimestampUtc = utcNowMinus15.AddMinutes(i) } ); } await _cloudWatchWrapper.PutMetricData(customMetricNamespace, customData); return customData; } /// <summary> /// Wrapper to add metric data to a CloudWatch metric. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricData">A data object for the metric data.</param> /// <returns>True if successful.</returns> public async Task<bool> PutMetricData(string metricNamespace, List<MetricDatum> metricData) { var putDataResponse = await _amazonCloudWatch.PutMetricDataAsync( new PutMetricDataRequest() { MetricData = metricData, Namespace = metricNamespace, }); return putDataResponse.HttpStatusCode == HttpStatusCode.OK; } • For API details, see PutMetricData in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 3085 Amazon CloudWatch User Guide Include the required files. #include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/PutMetricDataRequest.h> #include <iostream> Put data into the metric. Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::Dimension dimension; dimension.SetName("UNIQUE_PAGES"); dimension.SetValue("URLS"); Aws::CloudWatch::Model::MetricDatum datum; datum.SetMetricName("PAGES_VISITED"); datum.SetUnit(Aws::CloudWatch::Model::StandardUnit::None); datum.SetValue(data_point); datum.AddDimensions(dimension); Aws::CloudWatch::Model::PutMetricDataRequest request; request.SetNamespace("SITE/TRAFFIC"); request.AddMetricData(datum); auto outcome = cw.PutMetricData(request); if (!outcome.IsSuccess()) { std::cout << "Failed to put sample metric data:" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully put sample metric data" << std::endl; } • For API details, see PutMetricData in AWS SDK for C++ API Reference. Actions 3086 Amazon CloudWatch CLI AWS CLI User Guide To publish a custom metric to Amazon CloudWatch The following example uses the put-metric-data command to publish a custom metric to Amazon CloudWatch: aws cloudwatch put-metric-data --namespace "Usage Metrics" --metric-data file:// metric.json The values for the metric itself are stored in the JSON file, metric.json. Here are the contents of that file: [ { "MetricName": "New Posts", "Timestamp": "Wednesday, June 12, 2013 8:28:20 PM", "Value": 0.50, "Unit": "Count" } ] For more information, see Publishing Custom Metrics in the Amazon CloudWatch Developer Guide. To specify multiple dimensions The following example illustrates how to specify multiple dimensions. Each dimension is specified as a Name=Value pair. Multiple dimensions are separated by a comma.: aws cloudwatch put-metric-data --metric-name Buffers -- namespace MyNameSpace --unit Bytes --value 231434333 -- dimensions InstanceID=1-23456789,InstanceType=m1.small • For API details, see PutMetricData in AWS CLI Command Reference. Actions 3087 Amazon CloudWatch Java SDK for Java 2.x Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Adds metric
acw-ug-861
acw-ug.pdf
861
Custom Metrics in the Amazon CloudWatch Developer Guide. To specify multiple dimensions The following example illustrates how to specify multiple dimensions. Each dimension is specified as a Name=Value pair. Multiple dimensions are separated by a comma.: aws cloudwatch put-metric-data --metric-name Buffers -- namespace MyNameSpace --unit Bytes --value 231434333 -- dimensions InstanceID=1-23456789,InstanceType=m1.small • For API details, see PutMetricData in AWS CLI Command Reference. Actions 3087 Amazon CloudWatch Java SDK for Java 2.x Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Adds metric data for an alarm asynchronously. * * @param fileName the name of the JSON file containing the metric data * @return a CompletableFuture that asynchronously returns the PutMetricDataResponse */ public CompletableFuture<PutMetricDataResponse> addMetricDataForAlarmAsync(String fileName) { CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); return rootNode.toString(); // Return JSON as a string for further processing } catch (IOException e) { throw new RuntimeException("Failed to read file", e); } }); return readFileFuture.thenCompose(jsonContent -> { try { com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent); String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); Actions 3088 Amazon CloudWatch User Guide Instant instant = Instant.now(); // Create MetricDatum objects. MetricDatum datum1 = MetricDatum.builder() .metricName(customMetricName) .unit(StandardUnit.NONE) .value(1001.00) .timestamp(instant) .build(); MetricDatum datum2 = MetricDatum.builder() .metricName(customMetricName) .unit(StandardUnit.NONE) .value(1002.00) .timestamp(instant) .build(); List<MetricDatum> metricDataList = new ArrayList<>(); metricDataList.add(datum1); metricDataList.add(datum2); // Build the PutMetricData request. PutMetricDataRequest request = PutMetricDataRequest.builder() .namespace(customMetricNamespace) .metricData(metricDataList) .build(); // Send the request asynchronously. return getAsyncClient().putMetricData(request); } catch (IOException e) { CompletableFuture<PutMetricDataResponse> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(new RuntimeException("Failed to parse JSON content", e)); return failedFuture; } }).whenComplete((response, exception) -> { if (exception != null) { logger.error("Failed to put metric data: " + exception.getMessage(), exception); } else { logger.info("Added metric values for metric."); } Actions 3089 Amazon CloudWatch }); } User Guide • For API details, see PutMetricData in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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", Actions 3090 Amazon CloudWatch }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run(); User Guide Create the client in a separate module and export it. import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({}); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see PutMetricData in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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: [ Actions 3091 Amazon CloudWatch { User Guide 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)); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see PutMetricData in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun addMetricDataForAlarm(fileName: String?) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) Actions 3092 Amazon CloudWatch User Guide val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() // Set an Instant object. val time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT) val instant = Instant.parse(time) val datum = MetricDatum { metricName = customMetricName unit = StandardUnit.None value = 1001.00 timestamp = aws.smithy.kotlin.runtime.time .Instant(instant) } val datum2 = MetricDatum { metricName = customMetricName unit = StandardUnit.None value = 1002.00 timestamp = aws.smithy.kotlin.runtime.time .Instant(instant) } val metricDataList = ArrayList<MetricDatum>() metricDataList.add(datum) metricDataList.add(datum2) val request = PutMetricDataRequest { namespace = customMetricNamespace metricData = metricDataList } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putMetricData(request) println("Added metric values for for metric $customMetricName") } } Actions 3093 Amazon CloudWatch User Guide • For API details, see PutMetricData in AWS SDK for Kotlin API
acw-ug-862
acw-ug.pdf
862
time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT) val instant = Instant.parse(time) val datum = MetricDatum { metricName = customMetricName unit = StandardUnit.None value = 1001.00 timestamp = aws.smithy.kotlin.runtime.time .Instant(instant) } val datum2 = MetricDatum { metricName = customMetricName unit = StandardUnit.None value = 1002.00 timestamp = aws.smithy.kotlin.runtime.time .Instant(instant) } val metricDataList = ArrayList<MetricDatum>() metricDataList.add(datum) metricDataList.add(datum2) val request = PutMetricDataRequest { namespace = customMetricNamespace metricData = metricDataList } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putMetricData(request) println("Added metric values for for metric $customMetricName") } } Actions 3093 Amazon CloudWatch User Guide • For API details, see PutMetricData in AWS SDK for Kotlin API reference. PowerShell Tools for PowerShell Example 1: Creates a new MetricDatum object, and writes it to Amazon Web Services CloudWatch Metrics. ### Create a MetricDatum .NET object $Metric = New-Object -TypeName Amazon.CloudWatch.Model.MetricDatum $Metric.Timestamp = [DateTime]::UtcNow $Metric.MetricName = 'CPU' $Metric.Value = 50 ### Write the metric data to the CloudWatch service Write-CWMetricData -Namespace instance1 -MetricData $Metric • For API details, see PutMetricData in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource Actions 3094 Amazon CloudWatch User Guide def put_metric_data(self, namespace, name, value, unit): """ Sends a single data value to CloudWatch for a metric. This metric is given a timestamp of the current UTC time. :param namespace: The namespace of the metric. :param name: The name of the metric. :param value: The value of the metric. :param unit: The unit of the metric. """ try: metric = self.cloudwatch_resource.Metric(namespace, name) metric.put_data( Namespace=namespace, MetricData=[{"MetricName": name, "Value": value, "Unit": unit}], ) logger.info("Put data for metric %s.%s", namespace, name) except ClientError: logger.exception("Couldn't put data for metric %s.%s", namespace, name) raise Put a set of data into a CloudWatch metric. class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def put_metric_data_set(self, namespace, name, timestamp, unit, data_set): """ Sends a set of data to CloudWatch for a metric. All of the data in the set Actions 3095 Amazon CloudWatch User Guide have the same timestamp and unit. :param namespace: The namespace of the metric. :param name: The name of the metric. :param timestamp: The UTC timestamp for the metric. :param unit: The unit of the metric. :param data_set: The set of data to send. This set is a dictionary that contains a list of values and a list of corresponding counts. The value and count lists must be the same length. """ try: metric = self.cloudwatch_resource.Metric(namespace, name) metric.put_data( Namespace=namespace, MetricData=[ { "MetricName": name, "Timestamp": timestamp, "Values": data_set["values"], "Counts": data_set["counts"], "Unit": unit, } ], ) logger.info("Put data set for metric %s.%s.", namespace, name) except ClientError: logger.exception("Couldn't put data set for metric %s.%s.", namespace, name) raise • For API details, see PutMetricData in AWS SDK for Python (Boto3) API Reference. Actions 3096 Amazon CloudWatch Ruby SDK for Ruby Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-cloudwatch' # Adds a datapoint to a metric in Amazon CloudWatch. # # @param cloudwatch_client [Aws::CloudWatch::Client] # An initialized CloudWatch client. # @param metric_namespace [String] The namespace of the metric to add the # datapoint to. # @param metric_name [String] The name of the metric to add the datapoint to. # @param dimension_name [String] The name of the dimension to add the # datapoint to. # @param dimension_value [String] The value of the dimension to add the # datapoint to. # @param metric_value [Float] The value of the datapoint. # @param metric_unit [String] The unit of measurement for the datapoint. # @return [Boolean] # @example # exit 1 unless datapoint_added_to_metric?( # Aws::CloudWatch::Client.new(region: 'us-east-1'), # 'SITE/TRAFFIC', # 'UniqueVisitors', # 'SiteName', # 'example.com', # 5_885.0, # 'Count' # ) def datapoint_added_to_metric?( cloudwatch_client, metric_namespace, metric_name, dimension_name, dimension_value, Actions 3097 Amazon CloudWatch User Guide metric_value, metric_unit ) cloudwatch_client.put_metric_data( namespace: metric_namespace, metric_data: [ { metric_name: metric_name, dimensions: [ { name: dimension_name, value: dimension_value } ], value: metric_value, unit: metric_unit } ] ) puts "Added data about '#{metric_name}' to namespace " \ "'#{metric_namespace}'." true rescue StandardError => e puts "Error adding data about '#{metric_name}' to namespace " \ "'#{metric_namespace}': #{e.message}" false end • For API details, see PutMetricData in AWS SDK for Ruby API Reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Scenarios for CloudWatch using AWS SDKs The following code examples show you how to implement common scenarios in CloudWatch with AWS SDKs. These scenarios show you
acw-ug-863
acw-ug.pdf
863
"Added data about '#{metric_name}' to namespace " \ "'#{metric_namespace}'." true rescue StandardError => e puts "Error adding data about '#{metric_name}' to namespace " \ "'#{metric_namespace}': #{e.message}" false end • For API details, see PutMetricData in AWS SDK for Ruby API Reference. For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Scenarios for CloudWatch using AWS SDKs The following code examples show you how to implement common scenarios in CloudWatch with AWS SDKs. These scenarios show you how to accomplish specific tasks by calling multiple functions Scenarios 3098 Amazon CloudWatch User Guide within CloudWatch or combined with other AWS services. Each scenario includes a link to the complete source code, where you can find instructions on how to set up and run the code. Scenarios target an intermediate level of experience to help you understand service actions in context. Examples • Get started with CloudWatch alarms using an AWS SDK • Manage CloudWatch metrics and alarms using an AWS SDK • Monitor performance of Amazon DynamoDB using an AWS SDK Get started with CloudWatch alarms using an AWS SDK The following code example shows how to: • Create an alarm. • Disable alarm actions. • Describe an alarm. • Delete an alarm. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. DATA lt_alarmnames TYPE /aws1/cl_cwtalarmnames_w=>tt_alarmnames. DATA lo_alarmname TYPE REF TO /aws1/cl_cwtalarmnames_w. "Create an alarm" TRY. lo_cwt->putmetricalarm( iv_alarmname = iv_alarm_name Get started with alarms 3099 Amazon CloudWatch User Guide iv_comparisonoperator = iv_comparison_operator iv_evaluationperiods = iv_evaluation_periods iv_metricname = iv_metric_name iv_namespace = iv_namespace iv_statistic = iv_statistic iv_threshold = iv_threshold iv_actionsenabled = iv_actions_enabled iv_alarmdescription = iv_alarm_description iv_unit = iv_unit iv_period = iv_period it_dimensions = it_dimensions ). MESSAGE 'Alarm created' TYPE 'I'. CATCH /aws1/cx_cwtlimitexceededfault. MESSAGE 'The request processing has exceeded the limit' TYPE 'E'. ENDTRY. "Create an ABAP internal table for the created alarm." lo_alarmname = NEW #( iv_value = iv_alarm_name ). INSERT lo_alarmname INTO TABLE lt_alarmnames. "Disable alarm actions." TRY. lo_cwt->disablealarmactions( it_alarmnames = lt_alarmnames ). MESSAGE 'Alarm actions disabled' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_disablealarm_exception). DATA(lv_disablealarm_error) = |"{ lo_disablealarm_exception- >av_err_code }" - { lo_disablealarm_exception->av_err_msg }|. MESSAGE lv_disablealarm_error TYPE 'E'. ENDTRY. "Describe alarm using the same ABAP internal table." TRY. oo_result = lo_cwt->describealarms( " oo_result is returned for testing purpose " it_alarmnames = lt_alarmnames ). MESSAGE 'Alarms retrieved' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_describealarms_exception). DATA(lv_describealarms_error) = |"{ lo_describealarms_exception- >av_err_code }" - { lo_describealarms_exception->av_err_msg }|. MESSAGE lv_describealarms_error TYPE 'E'. ENDTRY. "Delete alarm." Get started with alarms 3100 Amazon CloudWatch TRY. User Guide lo_cwt->deletealarms( it_alarmnames = lt_alarmnames ). MESSAGE 'Alarms deleted' TYPE 'I'. CATCH /aws1/cx_cwtresourcenotfound. MESSAGE 'Resource being access is not found.' TYPE 'E'. ENDTRY. • For API details, see the following topics in AWS SDK for SAP ABAP API reference. • DeleteAlarms • DescribeAlarms • DisableAlarmActions • PutMetricAlarm For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Manage CloudWatch metrics and alarms using an AWS SDK The following code example shows how to: • Create an alarm to watch a CloudWatch metric. • Put data into a metric and trigger the alarm. • Get data from the alarm. • Delete the alarm. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Manage metrics and alarms 3101 Amazon CloudWatch User Guide Create a class that wraps CloudWatch operations. from datetime import datetime, timedelta import logging from pprint import pprint import random import time import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def put_metric_data_set(self, namespace, name, timestamp, unit, data_set): """ Sends a set of data to CloudWatch for a metric. All of the data in the set have the same timestamp and unit. :param namespace: The namespace of the metric. :param name: The name of the metric. :param timestamp: The UTC timestamp for the metric. :param unit: The unit of the metric. :param data_set: The set of data to send. This set is a dictionary that contains a list of values and a list of corresponding counts. The value and count lists must be the same length. """ try: metric = self.cloudwatch_resource.Metric(namespace, name) metric.put_data( Namespace=namespace, MetricData=[ { Manage metrics and alarms 3102 Amazon CloudWatch User Guide "MetricName": name, "Timestamp": timestamp, "Values": data_set["values"], "Counts": data_set["counts"], "Unit": unit, } ], ) logger.info("Put data set for metric %s.%s.", namespace, name) except ClientError: logger.exception("Couldn't put
acw-ug-864
acw-ug.pdf
864
name: The name of the metric. :param timestamp: The UTC timestamp for the metric. :param unit: The unit of the metric. :param data_set: The set of data to send. This set is a dictionary that contains a list of values and a list of corresponding counts. The value and count lists must be the same length. """ try: metric = self.cloudwatch_resource.Metric(namespace, name) metric.put_data( Namespace=namespace, MetricData=[ { Manage metrics and alarms 3102 Amazon CloudWatch User Guide "MetricName": name, "Timestamp": timestamp, "Values": data_set["values"], "Counts": data_set["counts"], "Unit": unit, } ], ) logger.info("Put data set for metric %s.%s.", namespace, name) except ClientError: logger.exception("Couldn't put data set for metric %s.%s.", namespace, name) raise def create_metric_alarm( self, metric_namespace, metric_name, alarm_name, stat_type, period, eval_periods, threshold, comparison_op, ): """ Creates an alarm that watches a metric. :param metric_namespace: The namespace of the metric. :param metric_name: The name of the metric. :param alarm_name: The name of the alarm. :param stat_type: The type of statistic the alarm watches. :param period: The period in which metric data are grouped to calculate statistics. :param eval_periods: The number of periods that the metric must be over the alarm threshold before the alarm is set into an alarmed state. :param threshold: The threshold value to compare against the metric statistic. :param comparison_op: The comparison operation used to compare the threshold Manage metrics and alarms 3103 Amazon CloudWatch User Guide against the metric. :return: The newly created alarm. """ try: metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name) alarm = metric.put_alarm( AlarmName=alarm_name, Statistic=stat_type, Period=period, EvaluationPeriods=eval_periods, Threshold=threshold, ComparisonOperator=comparison_op, ) logger.info( "Added alarm %s to track metric %s.%s.", alarm_name, metric_namespace, metric_name, ) except ClientError: logger.exception( "Couldn't add alarm %s to metric %s.%s", alarm_name, metric_namespace, metric_name, ) raise else: return alarm def put_metric_data(self, namespace, name, value, unit): """ Sends a single data value to CloudWatch for a metric. This metric is given a timestamp of the current UTC time. :param namespace: The namespace of the metric. :param name: The name of the metric. :param value: The value of the metric. :param unit: The unit of the metric. """ try: Manage metrics and alarms 3104 Amazon CloudWatch User Guide metric = self.cloudwatch_resource.Metric(namespace, name) metric.put_data( Namespace=namespace, MetricData=[{"MetricName": name, "Value": value, "Unit": unit}], ) logger.info("Put data for metric %s.%s", namespace, name) except ClientError: logger.exception("Couldn't put data for metric %s.%s", namespace, name) raise def get_metric_statistics(self, namespace, name, start, end, period, stat_types): """ Gets statistics for a metric within a specified time span. Metrics are grouped into the specified period. :param namespace: The namespace of the metric. :param name: The name of the metric. :param start: The UTC start time of the time span to retrieve. :param end: The UTC end time of the time span to retrieve. :param period: The period, in seconds, in which to group metrics. The period must match the granularity of the metric, which depends on the metric's age. For example, metrics that are older than three hours have a one-minute granularity, so the period must be at least 60 and must be a multiple of 60. :param stat_types: The type of statistics to retrieve, such as average value or maximum value. :return: The retrieved statistics for the metric. """ try: metric = self.cloudwatch_resource.Metric(namespace, name) stats = metric.get_statistics( StartTime=start, EndTime=end, Period=period, Statistics=stat_types ) logger.info( "Got %s statistics for %s.", len(stats["Datapoints"]), stats["Label"] Manage metrics and alarms 3105 Amazon CloudWatch ) User Guide except ClientError: logger.exception("Couldn't get statistics for %s.%s.", namespace, name) raise else: return stats def get_metric_alarms(self, metric_namespace, metric_name): """ Gets the alarms that are currently watching the specified metric. :param metric_namespace: The namespace of the metric. :param metric_name: The name of the metric. :returns: An iterator that yields the alarms. """ metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name) alarm_iter = metric.alarms.all() logger.info("Got alarms for metric %s.%s.", metric_namespace, metric_name) return alarm_iter def delete_metric_alarms(self, metric_namespace, metric_name): """ Deletes all of the alarms that are currently watching the specified metric. :param metric_namespace: The namespace of the metric. :param metric_name: The name of the metric. """ try: metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name) metric.alarms.delete() logger.info( "Deleted alarms for metric %s.%s.", metric_namespace, metric_name ) except ClientError: logger.exception( "Couldn't delete alarms for metric %s.%s.", metric_namespace, metric_name, Manage metrics and alarms 3106 Amazon CloudWatch User Guide ) raise Use the wrapper class to put data in a metric, trigger an alarm that watches the metric, and get data from the alarm. def usage_demo(): print("-" * 88) print("Welcome to the Amazon CloudWatch metrics and alarms demo!") print("-" * 88) logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") cw_wrapper = CloudWatchWrapper(boto3.resource("cloudwatch")) minutes = 20 metric_namespace = "doc-example-metric" metric_name = "page_views" start = datetime.utcnow() - timedelta(minutes=minutes) print( f"Putting data into metric {metric_namespace}.{metric_name} spanning the " f"last {minutes} minutes." ) for offset in range(0, minutes): stamp = start + timedelta(minutes=offset) cw_wrapper.put_metric_data_set( metric_namespace, metric_name, stamp, "Count", { "values": [ random.randint(bound, bound * 2) for bound in range(offset + 1, offset + 11) ], "counts": [random.randint(1, offset + 1) for _ in range(10)], }, )
acw-ug-865
acw-ug.pdf
865
metric, and get data from the alarm. def usage_demo(): print("-" * 88) print("Welcome to the Amazon CloudWatch metrics and alarms demo!") print("-" * 88) logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") cw_wrapper = CloudWatchWrapper(boto3.resource("cloudwatch")) minutes = 20 metric_namespace = "doc-example-metric" metric_name = "page_views" start = datetime.utcnow() - timedelta(minutes=minutes) print( f"Putting data into metric {metric_namespace}.{metric_name} spanning the " f"last {minutes} minutes." ) for offset in range(0, minutes): stamp = start + timedelta(minutes=offset) cw_wrapper.put_metric_data_set( metric_namespace, metric_name, stamp, "Count", { "values": [ random.randint(bound, bound * 2) for bound in range(offset + 1, offset + 11) ], "counts": [random.randint(1, offset + 1) for _ in range(10)], }, ) Manage metrics and alarms 3107 Amazon CloudWatch User Guide alarm_name = "high_page_views" period = 60 eval_periods = 2 print(f"Creating alarm {alarm_name} for metric {metric_name}.") alarm = cw_wrapper.create_metric_alarm( metric_namespace, metric_name, alarm_name, "Maximum", period, eval_periods, 100, "GreaterThanThreshold", ) print(f"Alarm ARN is {alarm.alarm_arn}.") print(f"Current alarm state is: {alarm.state_value}.") print( f"Sending data to trigger the alarm. This requires data over the threshold " f"for {eval_periods} periods of {period} seconds each." ) while alarm.state_value == "INSUFFICIENT_DATA": print("Sending data for the metric.") cw_wrapper.put_metric_data( metric_namespace, metric_name, random.randint(100, 200), "Count" ) alarm.load() print(f"Current alarm state is: {alarm.state_value}.") if alarm.state_value == "INSUFFICIENT_DATA": print(f"Waiting for {period} seconds...") time.sleep(period) else: print("Wait for a minute for eventual consistency of metric data.") time.sleep(period) if alarm.state_value == "OK": alarm.load() print(f"Current alarm state is: {alarm.state_value}.") print( f"Getting data for metric {metric_namespace}.{metric_name} during timespan " f"of {start} to {datetime.utcnow()} (times are UTC)." ) Manage metrics and alarms 3108 Amazon CloudWatch User Guide stats = cw_wrapper.get_metric_statistics( metric_namespace, metric_name, start, datetime.utcnow(), 60, ["Average", "Minimum", "Maximum"], ) print( f"Got {len(stats['Datapoints'])} data points for metric " f"{metric_namespace}.{metric_name}." ) pprint(sorted(stats["Datapoints"], key=lambda x: x["Timestamp"])) print(f"Getting alarms for metric {metric_name}.") alarms = cw_wrapper.get_metric_alarms(metric_namespace, metric_name) for alarm in alarms: print(f"Alarm {alarm.name} is currently in state {alarm.state_value}.") print(f"Deleting alarms for metric {metric_name}.") cw_wrapper.delete_metric_alarms(metric_namespace, metric_name) print("Thanks for watching!") print("-" * 88) • For API details, see the following topics in AWS SDK for Python (Boto3) API Reference. • DeleteAlarms • DescribeAlarmsForMetric • DisableAlarmActions • EnableAlarmActions • GetMetricStatistics • ListMetrics • PutMetricAlarm • PutMetricData Manage metrics and alarms 3109 Amazon CloudWatch User Guide For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Monitor performance of Amazon DynamoDB using an AWS SDK The following code example shows how to configure an application's use of DynamoDB to monitor performance. Java SDK for Java 2.x This example shows how to configure a Java application to monitor the performance of DynamoDB. The application sends metric data to CloudWatch where you can monitor the performance. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • CloudWatch • DynamoDB For a complete list of AWS SDK developer guides and code examples, see Using CloudWatch with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Monitor DynamoDB performance 3110 Amazon CloudWatch User Guide Security in Amazon CloudWatch Cloud security at AWS is the highest priority. As an AWS customer, you benefit from a data center and network architecture that is built to meet the requirements of the most security-sensitive organizations. Security is a shared responsibility between AWS and you. The shared responsibility model describes this as security of the cloud and security in the cloud: • Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in the AWS Cloud. AWS also provides you with services that you can use securely. Third- party auditors regularly test and verify the effectiveness of our security as part of the AWS Compliance Programs. To learn about the compliance programs that apply to CloudWatch, see AWS Services in Scope by Compliance Program. • Security in the cloud – Your responsibility is determined by the AWS service that you use. You are also responsible for other factors including the sensitivity of your data, your company’s requirements, and applicable laws and regulations This documentation helps you understand how to apply the shared responsibility model when using Amazon CloudWatch. It shows you how to configure Amazon CloudWatch to meet your security and compliance objectives. You also learn how to use other AWS services that help you to monitor and secure your CloudWatch resources. Contents • Data protection in Amazon CloudWatch • Identity and access management for Amazon CloudWatch • Compliance validation for Amazon CloudWatch • Resilience in Amazon CloudWatch • Infrastructure security in Amazon CloudWatch • AWS Security Hub • Using CloudWatch, CloudWatch Synthetics, and CloudWatch Network Monitoring with interface VPC endpoints • Security considerations for Synthetics canaries 3111 Amazon CloudWatch User Guide Data protection in Amazon CloudWatch The AWS shared responsibility model applies to data protection in
acw-ug-866
acw-ug.pdf
866
meet your security and compliance objectives. You also learn how to use other AWS services that help you to monitor and secure your CloudWatch resources. Contents • Data protection in Amazon CloudWatch • Identity and access management for Amazon CloudWatch • Compliance validation for Amazon CloudWatch • Resilience in Amazon CloudWatch • Infrastructure security in Amazon CloudWatch • AWS Security Hub • Using CloudWatch, CloudWatch Synthetics, and CloudWatch Network Monitoring with interface VPC endpoints • Security considerations for Synthetics canaries 3111 Amazon CloudWatch User Guide Data protection in Amazon CloudWatch The AWS shared responsibility model applies to data protection in Amazon CloudWatch. As described in this model, AWS is responsible for protecting the global infrastructure that runs all of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on this infrastructure. You are also responsible for the security configuration and management tasks for the AWS services that you use. For more information about data privacy, see the Data Privacy FAQ. For information about data protection in Europe, see the AWS Shared Responsibility Model and GDPR blog post on the AWS Security Blog. For data protection purposes, we recommend that you protect AWS account credentials and set up individual users with AWS IAM Identity Center or AWS Identity and Access Management (IAM). That way, each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways: • Use multi-factor authentication (MFA) with each account. • Use SSL/TLS to communicate with AWS resources. We require TLS 1.2 and recommend TLS 1.3. • Set up API and user activity logging with AWS CloudTrail. For information about using CloudTrail trails to capture AWS activities, see Working with CloudTrail trails in the AWS CloudTrail User Guide. • Use AWS encryption solutions, along with all default security controls within AWS services. • Use advanced managed security services such as Amazon Macie, which assists in discovering and securing sensitive data that is stored in Amazon S3. • If you require FIPS 140-3 validated cryptographic modules when accessing AWS through a command line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints, see Federal Information Processing Standard (FIPS) 140-3. We strongly recommend that you never put confidential or sensitive information, such as your customers' email addresses, into tags or free-form text fields such as a Name field. This includes when you work with CloudWatch or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into tags or free-form text fields used for names may be used for billing or diagnostic logs. If you provide a URL to an external server, we strongly recommend that you do not include credentials information in the URL to validate your request to that server. Data protection 3112 Amazon CloudWatch Encryption in transit User Guide CloudWatch uses end-to-end encryption of data in transit. For more information, see Encryption of data in transit. Identity and access management for Amazon CloudWatch AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be authenticated (signed in) and authorized (have permissions) to use CloudWatch resources. IAM is an AWS service that you can use with no additional charge. Topics • Audience • Authenticating with identities • Managing access using policies • How Amazon CloudWatch works with IAM • Identity-based policy examples for Amazon CloudWatch • Troubleshooting Amazon CloudWatch identity and access • CloudWatch dashboard permissions update • AWS managed (predefined) policies for CloudWatch • Customer managed policy examples • CloudWatch updates to AWS managed policies • Using condition keys to limit access to CloudWatch namespaces • Using condition keys to limit Contributor Insights users' access to log groups • Using condition keys to limit alarm actions • Using service-linked roles for CloudWatch • Using service-linked roles for CloudWatch RUM • Using service-linked roles for CloudWatch Application Insights • AWS managed policies for Amazon CloudWatch Application Insights • Amazon CloudWatch permissions reference Encryption in transit 3113 Amazon CloudWatch Audience User Guide How you use AWS Identity and Access Management (IAM) differs, depending on the work that you do in CloudWatch. Service user – If you use the CloudWatch service to do your job, then your administrator provides you with the credentials and permissions that you need. As you use more CloudWatch features to do your work, you might need additional permissions. Understanding how access is managed can help you request the right permissions from your administrator. If you cannot access a feature in CloudWatch, see Troubleshooting Amazon CloudWatch identity and access. Service administrator – If you're in charge of CloudWatch resources at your company, you probably have full access
acw-ug-867
acw-ug.pdf
867
(IAM) differs, depending on the work that you do in CloudWatch. Service user – If you use the CloudWatch service to do your job, then your administrator provides you with the credentials and permissions that you need. As you use more CloudWatch features to do your work, you might need additional permissions. Understanding how access is managed can help you request the right permissions from your administrator. If you cannot access a feature in CloudWatch, see Troubleshooting Amazon CloudWatch identity and access. Service administrator – If you're in charge of CloudWatch resources at your company, you probably have full access to CloudWatch. It's your job to determine which CloudWatch features and resources your service users should access. You must then submit requests to your IAM administrator to change the permissions of your service users. Review the information on this page to understand the basic concepts of IAM. To learn more about how your company can use IAM with CloudWatch, see How Amazon CloudWatch works with IAM. IAM administrator – If you're an IAM administrator, you might want to learn details about how you can write policies to manage access to CloudWatch. To view example CloudWatch identity-based policies that you can use in IAM, see Identity-based policy examples for Amazon CloudWatch. Authenticating with identities Authentication is how you sign in to AWS using your identity credentials. You must be authenticated (signed in to AWS) as the AWS account root user, as an IAM user, or by assuming an IAM role. You can sign in to AWS as a federated identity by using credentials provided through an identity source. AWS IAM Identity Center (IAM Identity Center) users, your company's single sign-on authentication, and your Google or Facebook credentials are examples of federated identities. When you sign in as a federated identity, your administrator previously set up identity federation using IAM roles. When you access AWS by using federation, you are indirectly assuming a role. Depending on the type of user you are, you can sign in to the AWS Management Console or the AWS access portal. For more information about signing in to AWS, see How to sign in to your AWS account in the AWS Sign-In User Guide. If you access AWS programmatically, AWS provides a software development kit (SDK) and a command line interface (CLI) to cryptographically sign your requests by using your credentials. If Audience 3114 Amazon CloudWatch User Guide you don't use AWS tools, you must sign requests yourself. For more information about using the recommended method to sign requests yourself, see AWS Signature Version 4 for API requests in the IAM User Guide. Regardless of the authentication method that you use, you might be required to provide additional security information. For example, AWS recommends that you use multi-factor authentication (MFA) to increase the security of your account. To learn more, see Multi-factor authentication in the AWS IAM Identity Center User Guide and AWS Multi-factor authentication in IAM in the IAM User Guide. AWS account root user When you create an AWS account, you begin with one sign-in identity that has complete access to all AWS services and resources in the account. This identity is called the AWS account root user and is accessed by signing in with the email address and password that you used to create the account. We strongly recommend that you don't use the root user for your everyday tasks. Safeguard your root user credentials and use them to perform the tasks that only the root user can perform. For the complete list of tasks that require you to sign in as the root user, see Tasks that require root user credentials in the IAM User Guide. Federated identity As a best practice, require human users, including users that require administrator access, to use federation with an identity provider to access AWS services by using temporary credentials. A federated identity is a user from your enterprise user directory, a web identity provider, the AWS Directory Service, the Identity Center directory, or any user that accesses AWS services by using credentials provided through an identity source. When federated identities access AWS accounts, they assume roles, and the roles provide temporary credentials. For centralized access management, we recommend that you use AWS IAM Identity Center. You can create users and groups in IAM Identity Center, or you can connect and synchronize to a set of users and groups in your own identity source for use across all your AWS accounts and applications. For information about IAM Identity Center, see What is IAM Identity Center? in the AWS IAM Identity Center User Guide. IAM users and groups An IAM user is an identity within your AWS account that has specific permissions for a single person or application. Where possible, we recommend relying on temporary credentials instead of
acw-ug-868
acw-ug.pdf
868
we recommend that you use AWS IAM Identity Center. You can create users and groups in IAM Identity Center, or you can connect and synchronize to a set of users and groups in your own identity source for use across all your AWS accounts and applications. For information about IAM Identity Center, see What is IAM Identity Center? in the AWS IAM Identity Center User Guide. IAM users and groups An IAM user is an identity within your AWS account that has specific permissions for a single person or application. Where possible, we recommend relying on temporary credentials instead of creating Authenticating with identities 3115 Amazon CloudWatch User Guide IAM users who have long-term credentials such as passwords and access keys. However, if you have specific use cases that require long-term credentials with IAM users, we recommend that you rotate access keys. For more information, see Rotate access keys regularly for use cases that require long- term credentials in the IAM User Guide. An IAM group is an identity that specifies a collection of IAM users. You can't sign in as a group. You can use groups to specify permissions for multiple users at a time. Groups make permissions easier to manage for large sets of users. For example, you could have a group named IAMAdmins and give that group permissions to administer IAM resources. Users are different from roles. A user is uniquely associated with one person or application, but a role is intended to be assumable by anyone who needs it. Users have permanent long-term credentials, but roles provide temporary credentials. To learn more, see Use cases for IAM users in the IAM User Guide. IAM roles An IAM role is an identity within your AWS account that has specific permissions. It is similar to an IAM user, but is not associated with a specific person. To temporarily assume an IAM role in the AWS Management Console, you can switch from a user to an IAM role (console). You can assume a role by calling an AWS CLI or AWS API operation or by using a custom URL. For more information about methods for using roles, see Methods to assume a role in the IAM User Guide. IAM roles with temporary credentials are useful in the following situations: • Federated user access – To assign permissions to a federated identity, you create a role and define permissions for the role. When a federated identity authenticates, the identity is associated with the role and is granted the permissions that are defined by the role. For information about roles for federation, see Create a role for a third-party identity provider (federation) in the IAM User Guide. If you use IAM Identity Center, you configure a permission set. To control what your identities can access after they authenticate, IAM Identity Center correlates the permission set to a role in IAM. For information about permissions sets, see Permission sets in the AWS IAM Identity Center User Guide. • Temporary IAM user permissions – An IAM user or role can assume an IAM role to temporarily take on different permissions for a specific task. • Cross-account access – You can use an IAM role to allow someone (a trusted principal) in a different account to access resources in your account. Roles are the primary way to grant cross- account access. However, with some AWS services, you can attach a policy directly to a resource Authenticating with identities 3116 Amazon CloudWatch User Guide (instead of using a role as a proxy). To learn the difference between roles and resource-based policies for cross-account access, see Cross account resource access in IAM in the IAM User Guide. • Cross-service access – Some AWS services use features in other AWS services. For example, when you make a call in a service, it's common for that service to run applications in Amazon EC2 or store objects in Amazon S3. A service might do this using the calling principal's permissions, using a service role, or using a service-linked role. • Forward access sessions (FAS) – When you use an IAM user or role to perform actions in AWS, you are considered a principal. When you use some services, you might perform an action that then initiates another action in a different service. FAS uses the permissions of the principal calling an AWS service, combined with the requesting AWS service to make requests to downstream services. FAS requests are only made when a service receives a request that requires interactions with other AWS services or resources to complete. In this case, you must have permissions to perform both actions. For policy details when making FAS requests, see Forward access sessions. • Service role – A service role is an IAM role that a service assumes to perform actions on your
acw-ug-869
acw-ug.pdf
869
might perform an action that then initiates another action in a different service. FAS uses the permissions of the principal calling an AWS service, combined with the requesting AWS service to make requests to downstream services. FAS requests are only made when a service receives a request that requires interactions with other AWS services or resources to complete. In this case, you must have permissions to perform both actions. For policy details when making FAS requests, see Forward access sessions. • Service role – A service role is an IAM role that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see Create a role to delegate permissions to an AWS service in the IAM User Guide. • Service-linked role – A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles. • Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials for applications that are running on an EC2 instance and making AWS CLI or AWS API requests. This is preferable to storing access keys within the EC2 instance. To assign an AWS role to an EC2 instance and make it available to all of its applications, you create an instance profile that is attached to the instance. An instance profile contains the role and enables programs that are running on the EC2 instance to get temporary credentials. For more information, see Use an IAM role to grant permissions to applications running on Amazon EC2 instances in the IAM User Guide. Managing access using policies You control access in AWS by creating policies and attaching them to AWS identities or resources. A policy is an object in AWS that, when associated with an identity or resource, defines their Managing access using policies 3117 Amazon CloudWatch User Guide permissions. AWS evaluates these policies when a principal (user, root user, or role session) makes a request. Permissions in the policies determine whether the request is allowed or denied. Most policies are stored in AWS as JSON documents. For more information about the structure and contents of JSON policy documents, see Overview of JSON policies in the IAM User Guide. Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. By default, users and roles have no permissions. To grant users permission to perform actions on the resources that they need, an IAM administrator can create IAM policies. The administrator can then add the IAM policies to roles, and users can assume the roles. IAM policies define permissions for an action regardless of the method that you use to perform the operation. For example, suppose that you have a policy that allows the iam:GetRole action. A user with that policy can get role information from the AWS Management Console, the AWS CLI, or the AWS API. Identity-based policies Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see Define custom IAM permissions with customer managed policies in the IAM User Guide. Identity-based policies can be further categorized as inline policies or managed policies. Inline policies are embedded directly into a single user, group, or role. Managed policies are standalone policies that you can attach to multiple users, groups, and roles in your AWS account. Managed policies include AWS managed policies and customer managed policies. To learn how to choose between a managed policy or an inline policy, see Choose between managed policies and inline policies in the IAM User Guide. Resource-based policies Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must specify a principal in a resource-based policy. Principals can include accounts, users, roles, federated users, or AWS services. Managing access using policies 3118 Amazon CloudWatch User Guide Resource-based policies are inline policies that are located in that service. You can't use AWS managed policies
acw-ug-870
acw-ug.pdf
870
policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must specify a principal in a resource-based policy. Principals can include accounts, users, roles, federated users, or AWS services. Managing access using policies 3118 Amazon CloudWatch User Guide Resource-based policies are inline policies that are located in that service. You can't use AWS managed policies from IAM in a resource-based policy. Access control lists (ACLs) Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format. Amazon S3, AWS WAF, and Amazon VPC are examples of services that support ACLs. To learn more about ACLs, see Access control list (ACL) overview in the Amazon Simple Storage Service Developer Guide. Other policy types AWS supports additional, less-common policy types. These policy types can set the maximum permissions granted to you by the more common policy types. • Permissions boundaries – A permissions boundary is an advanced feature in which you set the maximum permissions that an identity-based policy can grant to an IAM entity (IAM user or role). You can set a permissions boundary for an entity. The resulting permissions are the intersection of an entity's identity-based policies and its permissions boundaries. Resource-based policies that specify the user or role in the Principal field are not limited by the permissions boundary. An explicit deny in any of these policies overrides the allow. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. • Service control policies (SCPs) – SCPs are JSON policies that specify the maximum permissions for an organization or organizational unit (OU) in AWS Organizations. AWS Organizations is a service for grouping and centrally managing multiple AWS accounts that your business owns. If you enable all features in an organization, then you can apply service control policies (SCPs) to any or all of your accounts. The SCP limits permissions for entities in member accounts, including each AWS account root user. For more information about Organizations and SCPs, see Service control policies in the AWS Organizations User Guide. • Resource control policies (RCPs) – RCPs are JSON policies that you can use to set the maximum available permissions for resources in your accounts without updating the IAM policies attached to each resource that you own. The RCP limits permissions for resources in member accounts and can impact the effective permissions for identities, including the AWS account root user, regardless of whether they belong to your organization. For more information about Managing access using policies 3119 Amazon CloudWatch User Guide Organizations and RCPs, including a list of AWS services that support RCPs, see Resource control policies (RCPs) in the AWS Organizations User Guide. • Session policies – Session policies are advanced policies that you pass as a parameter when you programmatically create a temporary session for a role or federated user. The resulting session's permissions are the intersection of the user or role's identity-based policies and the session policies. Permissions can also come from a resource-based policy. An explicit deny in any of these policies overrides the allow. For more information, see Session policies in the IAM User Guide. Multiple policy types When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see Policy evaluation logic in the IAM User Guide. How Amazon CloudWatch works with IAM Before you use IAM to manage access to CloudWatch, learn what IAM features are available to use with CloudWatch. The following tables list the IAM features that you can use with Amazon CloudWatch. IAM feature CloudWatch support Identity-based policies Resource-based policies Policy actions Policy resources Policy condition keys (service-specific) ACLs ABAC (tags in policies) Temporary credentials Yes No Yes Yes Yes No Partial Yes How Amazon CloudWatch works with IAM 3120 Amazon CloudWatch IAM feature Principal permissions Service roles Service-linked roles CloudWatch support User Guide Yes Yes No To get a high-level view of how CloudWatch and other AWS services work with most IAM features, see AWS services that work with IAM in the IAM User Guide. Identity-based policies for CloudWatch Supports identity-based policies: Yes Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can perform, on which resources, and under what conditions.