You are viewing documentation for version 2 of the AWS SDK for Ruby. Version 3 documentation can be found here.

Class: Aws::CloudWatch::Metric

Inherits:
Resources::Resource show all
Defined in:
(unknown)

Instance Attribute Summary collapse

Attributes inherited from Resources::Resource

#client, #identifiers

Instance Method Summary collapse

Methods inherited from Resources::Resource

add_data_attribute, add_identifier, #data, data_attributes, #data_loaded?, identifiers, #load, #wait_until

Methods included from Resources::OperationMethods

#add_batch_operation, #add_operation, #batch_operation, #batch_operation_names, #batch_operations, #operation, #operation_names, #operations

Constructor Details

#initialize(namespace, name, options = {}) ⇒ Object #initialize(options = {}) ⇒ Object

Overloads:

  • #initialize(namespace, name, options = {}) ⇒ Object

    Parameters:

    • namespace (String)
    • name (String)

    Options Hash (options):

    • :client (Client)

      When `:client is not given, the options hash is used to construct a new Client object.

  • #initialize(options = {}) ⇒ Object

    Options Hash (options):

    • :namespace (required, String)
    • :name (required, String)
    • :client (Client)

      When `:client is not given, the options hash is used to construct a new Client object.

Instance Attribute Details

#dimensionsArray<Types::Dimension> (readonly)

The dimensions for the metric.

Returns:

#metric_nameString (readonly)

The name of the metric. This is a required field.

Returns:

  • (String)

    The name of the metric.

#nameString (readonly)

Returns:

  • (String)

#namespaceString (readonly)

Returns:

  • (String)

Instance Method Details

#alarms(options = {}) ⇒ Collection<Alarm>

Returns a Collection of Alarm resources. No API requests are made until you call an enumerable method on the collection. Client#describe_alarms_for_metric will be called multiple times until every Alarm has been yielded.

Examples:

Request syntax example with placeholder values


metric.alarms({
  statistic: "SampleCount", # accepts SampleCount, Average, Sum, Minimum, Maximum
  extended_statistic: "ExtendedStatistic",
  dimensions: [
    {
      name: "DimensionName", # required
      value: "DimensionValue", # required
    },
  ],
  period: 1,
  unit: "Seconds", # accepts 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
})

Enumerating Alarm resources.

metric.alarms.each do |alarm|
  # yields each alarm
end

Enumerating Alarm resources with a limit.

metric.alarms.limit(10).each do |alarm|
  # yields at most 10 alarms
end

Batch operations callable on the returned collection


# calls Client#delete_alarms on each batch
metric.alarms.batch_delete!

# calls Client#disable_alarm_actions on each batch
metric.alarms.batch_disable_actions

# calls Client#enable_alarm_actions on each batch
metric.alarms.batch_enable_actions

Options Hash (options):

  • :statistic (String)

    The statistic for the metric, other than percentiles. For percentile statistics, use ExtendedStatistics.

  • :extended_statistic (String)

    The percentile statistic for the metric. Specify a value between p0.0 and p100.

  • :dimensions (Array<Types::Dimension>)

    The dimensions associated with the metric. If the metric has any associated dimensions, you must specify them in order for the call to succeed.

  • :period (Integer)

    The period, in seconds, over which the statistic is applied.

  • :unit (String)

    The unit for the metric.

Returns:

See Also:

#get_statistics(options = {}) ⇒ Types::GetMetricStatisticsOutput

Gets statistics for the specified metric.

The maximum number of data points returned from a single call is 1,440. If you request more than 1,440 data points, CloudWatch returns an error. To reduce the number of data points, you can narrow the specified time range and make multiple requests across adjacent time ranges, or you can increase the specified period. Data points are not returned in chronological order.

CloudWatch aggregates data points based on the length of the period that you specify. For example, if you request statistics with a one-hour period, CloudWatch aggregates all data points with time stamps that fall within each one-hour period. Therefore, the number of values aggregated by CloudWatch is larger than the number of data points returned.

CloudWatch needs raw data points to calculate percentile statistics. If you publish data using a statistic set instead, you can only retrieve percentile statistics for this data if one of the following conditions is true:

  • The SampleCount value of the statistic set is 1.

  • The Min and the Max values of the statistic set are equal.

Percentile statistics are not available for metrics when any of the metric values are negative numbers.

Amazon CloudWatch retains metric data as follows:

  • Data points with a period of less than 60 seconds are available for 3 hours. These data points are high-resolution metrics and are available only for custom metrics that have been defined with a StorageResolution of 1.

  • Data points with a period of 60 seconds (1-minute) are available for 15 days.

  • Data points with a period of 300 seconds (5-minute) are available for 63 days.

  • Data points with a period of 3600 seconds (1 hour) are available for 455 days (15 months).

Data points that are initially published with a shorter period are aggregated together for long-term storage. For example, if you collect data using a period of 1 minute, the data remains available for 15 days with 1-minute resolution. After 15 days, this data is still available, but is aggregated and retrievable only with a resolution of 5 minutes. After 63 days, the data is further aggregated and is available with a resolution of 1 hour.

CloudWatch started retaining 5-minute and 1-hour metric data as of July 9, 2016.

For information about metrics and dimensions supported by AWS services, see the Amazon CloudWatch Metrics and Dimensions Reference in the Amazon CloudWatch User Guide.

Examples:

Request syntax example with placeholder values


metric.get_statistics({
  dimensions: [
    {
      name: "DimensionName", # required
      value: "DimensionValue", # required
    },
  ],
  start_time: Time.now, # required
  end_time: Time.now, # required
  period: 1, # required
  statistics: ["SampleCount"], # accepts SampleCount, Average, Sum, Minimum, Maximum
  extended_statistics: ["ExtendedStatistic"],
  unit: "Seconds", # accepts 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
})

Options Hash (options):

  • :dimensions (Array<Types::Dimension>)

    The dimensions. If the metric contains multiple dimensions, you must include a value for each dimension. CloudWatch treats each unique combination of dimensions as a separate metric. If a specific combination of dimensions was not published, you can\'t retrieve statistics for it. You must specify the same dimensions that were used when the metrics were created. For an example, see Dimension Combinations in the Amazon CloudWatch User Guide. For more information about specifying dimensions, see Publishing Metrics in the Amazon CloudWatch User Guide.

  • :start_time (required, Time)

    The time stamp that determines the first data point to return. Start times are evaluated relative to the time that CloudWatch receives the request.

    The value specified is inclusive; results include data points with the specified time stamp. In a raw HTTP query, the time stamp must be in ISO 8601 UTC format (for example, 2016-10-03T23:00:00Z).

    CloudWatch rounds the specified time stamp as follows:

    • Start time less than 15 days ago - Round down to the nearest whole minute. For example, 12:32:34 is rounded down to 12:32:00.

    • Start time between 15 and 63 days ago - Round down to the nearest 5-minute clock interval. For example, 12:32:34 is rounded down to 12:30:00.

    • Start time greater than 63 days ago - Round down to the nearest 1-hour clock interval. For example, 12:32:34 is rounded down to 12:00:00.

    If you set Period to 5, 10, or 30, the start time of your request is rounded down to the nearest time that corresponds to even 5-, 10-, or 30-second divisions of a minute. For example, if you make a query at (HH:mm:ss) 01:05:23 for the previous 10-second period, the start time of your request is rounded down and you receive data from 01:05:10 to 01:05:20. If you make a query at 15:07:17 for the previous 5 minutes of data, using a period of 5 seconds, you receive data timestamped between 15:02:15 and 15:07:15.

  • :end_time (required, Time)

    The time stamp that determines the last data point to return.

    The value specified is exclusive; results include data points up to the specified time stamp. In a raw HTTP query, the time stamp must be in ISO 8601 UTC format (for example, 2016-10-10T23:00:00Z).

  • :period (required, Integer)

    The granularity, in seconds, of the returned data points. For metrics with regular resolution, a period can be as short as one minute (60 seconds) and must be a multiple of 60. For high-resolution metrics that are collected at intervals of less than one minute, the period can be 1, 5, 10, 30, 60, or any multiple of 60. High-resolution metrics are those metrics stored by a PutMetricData call that includes a StorageResolution of 1 second.

    If the StartTime parameter specifies a time stamp that is greater than 3 hours ago, you must specify the period as follows or no data points in that time range is returned:

    • Start time between 3 hours and 15 days ago - Use a multiple of 60 seconds (1 minute).

    • Start time between 15 and 63 days ago - Use a multiple of 300 seconds (5 minutes).

    • Start time greater than 63 days ago - Use a multiple of 3600 seconds (1 hour).

  • :statistics (Array<String>)

    The metric statistics, other than percentile. For percentile statistics, use ExtendedStatistics. When calling GetMetricStatistics, you must specify either Statistics or ExtendedStatistics, but not both.

  • :extended_statistics (Array<String>)

    The percentile statistics. Specify values between p0.0 and p100. When calling GetMetricStatistics, you must specify either Statistics or ExtendedStatistics, but not both. Percentile statistics are not available for metrics when any of the metric values are negative numbers.

  • :unit (String)

    The unit for a given metric. If you omit Unit, all data that was collected with any unit is returned, along with the corresponding units that were specified when the data was reported to CloudWatch. If you specify a unit, the operation returns only data that was collected with that unit specified. If you specify a unit that does not match the data collected, the results of the operation are null. CloudWatch does not perform unit conversions.

Returns:

See Also:

#put_alarm(options = {}) ⇒ Alarm

Examples:

Request syntax example with placeholder values


metric.put_alarm({
  alarm_name: "AlarmName", # required
  alarm_description: "AlarmDescription",
  actions_enabled: false,
  ok_actions: ["ResourceName"],
  alarm_actions: ["ResourceName"],
  insufficient_data_actions: ["ResourceName"],
  statistic: "SampleCount", # accepts SampleCount, Average, Sum, Minimum, Maximum
  extended_statistic: "ExtendedStatistic",
  dimensions: [
    {
      name: "DimensionName", # required
      value: "DimensionValue", # required
    },
  ],
  period: 1,
  unit: "Seconds", # accepts 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
  evaluation_periods: 1, # required
  datapoints_to_alarm: 1,
  threshold: 1.0,
  comparison_operator: "GreaterThanOrEqualToThreshold", # required, accepts GreaterThanOrEqualToThreshold, GreaterThanThreshold, LessThanThreshold, LessThanOrEqualToThreshold, LessThanLowerOrGreaterThanUpperThreshold, LessThanLowerThreshold, GreaterThanUpperThreshold
  treat_missing_data: "TreatMissingData",
  evaluate_low_sample_count_percentile: "EvaluateLowSampleCountPercentile",
  metrics: [
    {
      id: "MetricId", # required
      metric_stat: {
        metric: { # required
          namespace: "Namespace",
          metric_name: "MetricName",
          dimensions: [
            {
              name: "DimensionName", # required
              value: "DimensionValue", # required
            },
          ],
        },
        period: 1, # required
        stat: "Stat", # required
        unit: "Seconds", # accepts 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
      },
      expression: "MetricExpression",
      label: "MetricLabel",
      return_data: false,
      period: 1,
    },
  ],
  tags: [
    {
      key: "TagKey", # required
      value: "TagValue", # required
    },
  ],
  threshold_metric_id: "MetricId",
})

Basic usage

alarm = metric.put_alarm(options)
alarm.name
#=> "alarm-name"

Options Hash (options):

  • :alarm_name (required, String)

    The name for the alarm. This name must be unique within the Region.

  • :alarm_description (String)

    The description for the alarm.

  • :actions_enabled (Boolean)

    Indicates whether actions should be executed during any changes to the alarm state. The default is TRUE.

  • :ok_actions (Array<String>)

    The actions to execute when this alarm transitions to an OK state from any other state. Each action is specified as an Amazon Resource Name (ARN).

    Valid Values: arn:aws:automate:region:ec2:stop | arn:aws:automate:region:ec2:terminate | arn:aws:automate:region:ec2:recover | arn:aws:automate:region:ec2:reboot | arn:aws:sns:region:account-id:sns-topic-name | arn:aws:autoscaling:region:account-id:scalingPolicy:policy-id:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name

    Valid Values (for use with IAM roles): arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Stop/1.0 | arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Terminate/1.0 | arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Reboot/1.0

  • :alarm_actions (Array<String>)

    The actions to execute when this alarm transitions to the ALARM state from any other state. Each action is specified as an Amazon Resource Name (ARN).

    Valid Values: arn:aws:automate:region:ec2:stop | arn:aws:automate:region:ec2:terminate | arn:aws:automate:region:ec2:recover | arn:aws:automate:region:ec2:reboot | arn:aws:sns:region:account-id:sns-topic-name | arn:aws:autoscaling:region:account-id:scalingPolicy:policy-id:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name

    Valid Values (for use with IAM roles): arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Stop/1.0 | arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Terminate/1.0 | arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Reboot/1.0

  • :insufficient_data_actions (Array<String>)

    The actions to execute when this alarm transitions to the INSUFFICIENT_DATA state from any other state. Each action is specified as an Amazon Resource Name (ARN).

    Valid Values: arn:aws:automate:region:ec2:stop | arn:aws:automate:region:ec2:terminate | arn:aws:automate:region:ec2:recover | arn:aws:automate:region:ec2:reboot | arn:aws:sns:region:account-id:sns-topic-name | arn:aws:autoscaling:region:account-id:scalingPolicy:policy-id:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name

    Valid Values (for use with IAM roles): >arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Stop/1.0 | arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Terminate/1.0 | arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Reboot/1.0

  • :statistic (String)

    The statistic for the metric specified in MetricName, other than percentile. For percentile statistics, use ExtendedStatistic. When you call PutMetricAlarm and specify a MetricName, you must specify either Statistic or ExtendedStatistic, but not both.

  • :extended_statistic (String)

    The percentile statistic for the metric specified in MetricName. Specify a value between p0.0 and p100. When you call PutMetricAlarm and specify a MetricName, you must specify either Statistic or ExtendedStatistic, but not both.

  • :dimensions (Array<Types::Dimension>)

    The dimensions for the metric specified in MetricName.

  • :period (Integer)

    The length, in seconds, used each time the metric specified in MetricName is evaluated. Valid values are 10, 30, and any multiple of 60.

    Period is required for alarms based on static thresholds. If you are creating an alarm based on a metric math expression, you specify the period for each metric within the objects in the Metrics array.

    Be sure to specify 10 or 30 only for metrics that are stored by a PutMetricData call with a StorageResolution of 1. If you specify a period of 10 or 30 for a metric that does not have sub-minute resolution, the alarm still attempts to gather data at the period rate that you specify. In this case, it does not receive data for the attempts that do not correspond to a one-minute data resolution, and the alarm might often lapse into INSUFFICENT_DATA status. Specifying 10 or 30 also sets this alarm as a high-resolution alarm, which has a higher charge than other alarms. For more information about pricing, see Amazon CloudWatch Pricing.

    An alarm\'s total current evaluation period can be no longer than one day, so Period multiplied by EvaluationPeriods cannot be more than 86,400 seconds.

  • :unit (String)

    The unit of measure for the statistic. For example, the units for the Amazon EC2 NetworkIn metric are Bytes because NetworkIn tracks the number of bytes that an instance receives on all network interfaces. You can also specify a unit when you create a custom metric. Units help provide conceptual meaning to your data. Metric data points that specify a unit of measure, such as Percent, are aggregated separately.

    If you don\'t specify Unit, CloudWatch retrieves all unit types that have been published for the metric and attempts to evaluate the alarm. Usually, metrics are published with only one unit, so the alarm works as intended.

    However, if the metric is published with multiple types of units and you don\'t specify a unit, the alarm\'s behavior is not defined and it behaves predictably.

    We recommend omitting Unit so that you don\'t inadvertently specify an incorrect unit that is not published for this metric. Doing so causes the alarm to be stuck in the INSUFFICIENT DATA state.

  • :evaluation_periods (required, Integer)

    The number of periods over which data is compared to the specified threshold. If you are setting an alarm that requires that a number of consecutive data points be breaching to trigger the alarm, this value specifies that number. If you are setting an \"M out of N\" alarm, this value is the N.

    An alarm\'s total current evaluation period can be no longer than one day, so this number multiplied by Period cannot be more than 86,400 seconds.

  • :datapoints_to_alarm (Integer)

    The number of data points that must be breaching to trigger the alarm. This is used only if you are setting an \"M out of N\" alarm. In that case, this value is the M. For more information, see Evaluating an Alarm in the Amazon CloudWatch User Guide.

  • :threshold (Float)

    The value against which the specified statistic is compared.

    This parameter is required for alarms based on static thresholds, but should not be used for alarms based on anomaly detection models.

  • :comparison_operator (required, String)

    The arithmetic operation to use when comparing the specified statistic and threshold. The specified statistic value is used as the first operand.

    The values LessThanLowerOrGreaterThanUpperThreshold, LessThanLowerThreshold, and GreaterThanUpperThreshold are used only for alarms based on anomaly detection models.

  • :treat_missing_data (String)

    Sets how this alarm is to handle missing data points. If TreatMissingData is omitted, the default behavior of missing is used. For more information, see Configuring How CloudWatch Alarms Treats Missing Data.

    Valid Values: breaching | notBreaching | ignore | missing

  • :evaluate_low_sample_count_percentile (String)

    Used only for alarms based on percentiles. If you specify ignore, the alarm state does not change during periods with too few data points to be statistically significant. If you specify evaluate or omit this parameter, the alarm is always evaluated and possibly changes state no matter how many data points are available. For more information, see Percentile-Based CloudWatch Alarms and Low Data Samples.

    Valid Values: evaluate | ignore

  • :metrics (Array<Types::MetricDataQuery>)

    An array of MetricDataQuery structures that enable you to create an alarm based on the result of a metric math expression. For each PutMetricAlarm operation, you must specify either MetricName or a Metrics array.

    Each item in the Metrics array either retrieves a metric or performs a math expression.

    One item in the Metrics array is the expression that the alarm watches. You designate this expression by setting ReturnData to true for this object in the array. For more information, see MetricDataQuery.

    If you use the Metrics parameter, you cannot include the MetricName, Dimensions, Period, Namespace, Statistic, or ExtendedStatistic parameters of PutMetricAlarm in the same operation. Instead, you retrieve the metrics you are using in your math expression as part of the Metrics array.

  • :tags (Array<Types::Tag>)

    A list of key-value pairs to associate with the alarm. You can associate as many as 50 tags with an alarm.

    Tags can help you organize and categorize your resources. You can also use them to scope user permissions by granting a user permission to access or change only resources with certain tag values.

  • :threshold_metric_id (String)

    If this is an alarm based on an anomaly detection model, make this value match the ID of the ANOMALY_DETECTION_BAND function.

    For an example of how to use this parameter, see the Anomaly Detection Model Alarm example on this page.

    If your alarm uses this parameter, it cannot have Auto Scaling actions.

Returns:

See Also:

#put_dataStruct

Publishes metric data points to Amazon CloudWatch. CloudWatch associates the data points with the specified metric. If the specified metric does not exist, CloudWatch creates the metric. When CloudWatch creates a metric, it can take up to fifteen minutes for the metric to appear in calls to ListMetrics.

You can publish either individual data points in the Value field, or arrays of values and the number of times each value occurred during the period by using the Values and Counts fields in the MetricDatum structure. Using the Values and Counts method enables you to publish up to 150 values per metric with one PutMetricData request, and supports retrieving percentile statistics on this data.

Each PutMetricData request is limited to 40 KB in size for HTTP POST requests. You can send a payload compressed by gzip. Each request is also limited to no more than 20 different metrics.

Although the Value parameter accepts numbers of type Double, CloudWatch rejects values that are either too small or too large. Values must be in the range of -2360 to 2360. In addition, special values (for example, NaN, +Infinity, -Infinity) are not supported.

You can use up to 10 dimensions per metric to further clarify what data the metric collects. Each dimension consists of a Name and Value pair. For more information about specifying dimensions, see Publishing Metrics in the Amazon CloudWatch User Guide.

You specify the time stamp to be associated with each data point. You can specify time stamps that are as much as two weeks before the current date, and as much as 2 hours after the current day and time.

Data points with time stamps from 24 hours ago or longer can take at least 48 hours to become available for GetMetricData or GetMetricStatistics from the time they are submitted. Data points with time stamps between 3 and 24 hours ago can take as much as 2 hours to become available for for GetMetricData or GetMetricStatistics.

CloudWatch needs raw data points to calculate percentile statistics. If you publish data using a statistic set instead, you can only retrieve percentile statistics for this data if one of the following conditions is true:

  • The SampleCount value of the statistic set is 1 and Min, Max, and Sum are all equal.

  • The Min and Max are equal, and Sum is equal to Min multiplied by SampleCount.

Examples:

Request syntax example with placeholder values


metric.put_data()

Returns:

  • (Struct)

    Returns an empty response.

See Also: