AWSCDK::CloudWatch

108 types

Amazon CloudWatch Construct Library

Metric objects

Metric objects represent a metric that is emitted by AWS services or your own application, such as CPUUsage, FailureCount or Bandwidth.

Metric objects can be constructed directly or are exposed by resources as attributes. Resources that expose metrics will have functions that look like metric_xxx() which will return a Metric object, initialized with defaults that make sense.

For example, lambda.Function objects have the fn.metricErrors() method, which represents the amount of errors reported by that Lambda function:

fn = nil # AWSCDK::Lambda::Function


errors = fn.metric_errors

Metric objects can be account and region aware. You can specify account and region as properties of the metric, or use the metric.attachTo(Construct) method. metric.attachTo() will automatically copy the region and account fields of the Construct, which can come from anywhere in the Construct tree.

You can also instantiate Metric objects to reference any published metric that's not exposed using a convenience method on the CDK construct. For example:

hosted_zone = AWSCDK::Route53::HostedZone.new(self, "MyHostedZone", {zone_name: "example.org"})
metric = AWSCDK::CloudWatch::Metric.new({
    namespace: "AWS/Route53",
    metric_name: "DNSQueries",
    dimensions_map: {
        HostedZoneId: hosted_zone.hosted_zone_id,
    },
})

Instantiating a new Metric object

If you want to reference a metric that is not yet exposed by an existing construct, you can instantiate a Metric object to represent it. For example:

metric = AWSCDK::CloudWatch::Metric.new({
    namespace: "MyNamespace",
    metric_name: "MyMetric",
    dimensions_map: {
        ProcessingStep: "Download",
    },
})

Metric ID

Metrics can be assigned a unique identifier using the id property. This is useful when referencing metrics in math expressions:

metric = AWSCDK::CloudWatch::Metric.new({
    namespace: "AWS/Lambda",
    metric_name: "Invocations",
    dimensions_map: {
        FunctionName: "MyFunction",
    },
    id: "invocations",
})

The id must start with a lowercase letter and can only contain letters, numbers, and underscores.

Metric Visible

Metrics can be hidden from dashboard graphs using the visible property:

fn = nil # AWSCDK::Lambda::Function


metric = fn.metric_errors({
    visible: false,
})

By default, all metrics are visible (visible: true). Setting visible: false hides the metric from dashboard visualizations while still allowing it to be used in math expressions given that it has an id set to it.

Metric Math

Math expressions are supported by instantiating the MathExpression class. For example, a math expression that sums two other metrics looks like this:

fn = nil # AWSCDK::Lambda::Function


all_problems = AWSCDK::CloudWatch::MathExpression.new({
    expression: "errors + throttles",
    using_metrics: {
        errors: fn.metric_errors,
        throttles: fn.metric_throttles,
    },
})

You can use MathExpression objects like any other metric, including using them in other math expressions:

fn = nil # AWSCDK::Lambda::Function
all_problems = nil # AWSCDK::CloudWatch::MathExpression


problem_percentage = AWSCDK::CloudWatch::MathExpression.new({
    expression: "(problems / invocations) * 100",
    using_metrics: {
        problems: all_problems,
        invocations: fn.metric_invocations,
    },
})

Metric ID Usage in Math Expressions

When metrics have custom IDs, you can reference them directly in math expressions.

fn = nil # AWSCDK::Lambda::Function


invocations = fn.metric_invocations({
    id: "lambda_invocations",
})

errors = fn.metric_errors({
    id: "lambda_errors",
})

When metrics have predefined IDs, they can be referenced directly in math expressions by their ID without requiring the using_metrics property.

error_rate = AWSCDK::CloudWatch::MathExpression.new({
    expression: "lambda_errors / lambda_invocations * 100",
    label: "Error Rate (%)",
})

Search Expressions

Search expressions allow you to dynamically discover and display metrics that match specific criteria, making them ideal for monitoring dynamic infrastructure where the exact metrics aren't known in advance. A single search expression can return up to 500 time series.

Using SearchExpression Class

Following is an example of a search expression that returns all CPUUtilization metrics with the graph showing the Average statistic with an aggregation period of 5 minutes:

cpu_utilization = AWSCDK::CloudWatch::SearchExpression.new({
    expression: "SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 900)",
    label: "EC2 CPU Utilization",
    color: "#ff7f0e",
})

Cross-account and cross-region search expressions are also supported. Use the search_account and search_region properties to specify the account and/or region to evaluate the search expression against.

 = AWSCDK::CloudWatch::SearchExpression.new({
    expression: "SEARCH('{AWS/Lambda,FunctionName} MetricName=\"Invocations\"', 'Sum', 300)",
    search_account: "123456789012",
    search_region: "us-west-2",
    label: "Production Lambda Invocations",
})

Aggregation

To graph or alarm on metrics you must aggregate them first, using a function like Average or a percentile function like P99. By default, most Metric objects returned by CDK libraries will be configured as Average over 300 seconds (5 minutes). The exception is if the metric represents a count of discrete events, such as failures. In that case, the Metric object will be configured as Sum over 300 seconds, i.e. it represents the number of times that event occurred over the time period.

If you want to change the default aggregation of the Metric object (for example, the function or the period), you can do so by passing additional parameters to the metric function call:

fn = nil # AWSCDK::Lambda::Function


minute_error_rate = fn.metric_errors({
    statistic: AWSCDK::CloudWatch::Stats.AVERAGE,
    period: AWSCDK::Duration.minutes(1),
    label: "Lambda failure rate",
})

The statistic field accepts a string; the cloudwatch.Stats object has a number of predefined factory functions that help you constructs strings that are appropriate for CloudWatch. The metric_errors function also allows changing the metric label or color, which will be useful when embedding them in graphs (see below).

Rates versus Sums

The reason for using Sum to count discrete events is that some events are emitted as either 0 or 1 (for example Errors for a Lambda) and some are only emitted as 1 (for example NumberOfMessagesPublished for an SNS topic).

In case 0-metrics are emitted, it makes sense to take the Average of this metric: the result will be the fraction of errors over all executions.

If 0-metrics are not emitted, the Average will always be equal to 1, and not be very useful.

In order to simplify the mental model of Metric objects, we default to aggregating using Sum, which will be the same for both metrics types. If you happen to know the Metric you want to alarm on makes sense as a rate (Average) you can always choose to change the statistic.

Available Aggregation Statistics

For your metrics aggregation, you can use the following statistics:

Statistic Short format Long format Factory name
SampleCount (n) Stats.SAMPLE_COUNT
Average (avg) Stats.AVERAGE
Sum Stats.SUM
Minimum (min) Stats.MINIMUM
Maximum (max) Stats.MAXIMUM
Interquartile mean (IQM) Stats.IQM
Percentile (p) p99 Stats.p(99)
Winsorized mean (WM) wm99 = WM(:99%) `WM(x:y) \ WM(x%:y%) \
Trimmed count (TC) tc99 = TC(:99%) `TC(x:y) \ TC(x%:y%) \
Trimmed sum (TS) ts99 = TS(:99%) `TS(x:y) \ TS(x%:y%) \
Percentile rank (PR) `PR(x:y) \ PR(x:) \

The most common values are provided in the cloudwatch.Stats class. You can provide any string if your statistic is not in the class.

Read more at CloudWatch statistics definitions.

hosted_zone = nil # AWSCDK::Route53::HostedZone


AWSCDK::CloudWatch::Metric.new({
    namespace: "AWS/Route53",
    metric_name: "DNSQueries",
    dimensions_map: {
        HostedZoneId: hosted_zone.hosted_zone_id,
    },
    statistic: AWSCDK::CloudWatch::Stats.SAMPLE_COUNT,
    period: AWSCDK::Duration.minutes(5),
})

AWSCDK::CloudWatch::Metric.new({
    namespace: "AWS/Route53",
    metric_name: "DNSQueries",
    dimensions_map: {
        HostedZoneId: hosted_zone.hosted_zone_id,
    },
    statistic: AWSCDK::CloudWatch::Stats.p(99),
    period: AWSCDK::Duration.minutes(5),
})

AWSCDK::CloudWatch::Metric.new({
    namespace: "AWS/Route53",
    metric_name: "DNSQueries",
    dimensions_map: {
        HostedZoneId: hosted_zone.hosted_zone_id,
    },
    statistic: "TS(7.5%:90%)",
    period: AWSCDK::Duration.minutes(5),
})

Labels

Metric labels are displayed in the legend of graphs that include the metrics.

You can use dynamic labels to show summary information about the displayed time series in the legend. For example, if you use:

fn = nil # AWSCDK::Lambda::Function


minute_error_rate = fn.metric_errors({
    statistic: AWSCDK::CloudWatch::Stats.SUM,
    period: AWSCDK::Duration.hours(1),

    # Show the maximum hourly error count in the legend
    label: "[max: ${MAX}] Lambda failure rate",
})

As the metric label, the maximum value in the visible range will be shown next to the time series name in the graph's legend.

If the metric is a math expression producing more than one time series, the maximum will be individually calculated and shown for each time series produce by the math expression.

Alarms

Alarms can be created on metrics in one of two ways. Either create an Alarm object, passing the Metric object to set the alarm on:

fn = nil # AWSCDK::Lambda::Function


AWSCDK::CloudWatch::Alarm.new(self, "Alarm", {
    metric: fn.metric_errors,
    threshold: 100,
    evaluation_periods: 2,
})

Alternatively, you can call metric.createAlarm():

fn = nil # AWSCDK::Lambda::Function


fn.metric_errors.create_alarm(self, "Alarm", {
    threshold: 100,
    evaluation_periods: 2,
})

The most important properties to set while creating an Alarms are:

To create a cross-account alarm, make sure you have enabled cross-account functionality in CloudWatch. Then, set the account property in the Metric object either manually or via the metric.attachTo() method.

Please note that it is not possible to:

Alarm Actions

To add actions to an alarm, use the integration classes from the aws-cdk-lib/aws-cloudwatch-actions package. For example, to post a message to an SNS topic when an alarm breaches, do the following:

require 'aws-cdk-lib'
alarm = nil # AWSCDK::CloudWatch::Alarm


topic = AWSCDK::SNS::Topic.new(self, "Topic")
alarm.add_alarm_action(AWSCDK::CloudWatchActions::SNSAction.new(topic))

Notification formats

Alarms can be created in one of two "formats":

For backwards compatibility, CDK will try to create classic, top-level CloudWatch alarms as much as possible, unless you are using features that cannot be expressed in that format. Features that require the new-style alarm format are:

The difference between these two does not impact the functionality of the alarm in any way, except that the format of the notifications the Alarm generates is different between them. This affects both the notifications sent out over SNS, as well as the EventBridge events generated by this Alarm. If you are writing code to consume these notifications, be sure to handle both formats.

Composite Alarms

Composite Alarms can be created from existing Alarm resources.

alarm1 = nil # AWSCDK::CloudWatch::Alarm
alarm2 = nil # AWSCDK::CloudWatch::Alarm
alarm3 = nil # AWSCDK::CloudWatch::Alarm
alarm4 = nil # AWSCDK::CloudWatch::Alarm


alarm_rule = AWSCDK::CloudWatch::AlarmRule.any_of(AWSCDK::CloudWatch::AlarmRule.all_of(AWSCDK::CloudWatch::AlarmRule.any_of(alarm1, AWSCDK::CloudWatch::AlarmRule.from_alarm(alarm2, AWSCDK::CloudWatch::AlarmState::OK), alarm3), AWSCDK::CloudWatch::AlarmRule._not(AWSCDK::CloudWatch::AlarmRule.from_alarm(alarm4, AWSCDK::CloudWatch::AlarmState::INSUFFICIENT_DATA))), AWSCDK::CloudWatch::AlarmRule.from_boolean(false))

AWSCDK::CloudWatch::CompositeAlarm.new(self, "MyAwesomeCompositeAlarm", {
    alarm_rule: alarm_rule,
})

Actions Suppressor

If you want to disable actions of a Composite Alarm based on a certain condition, you can use Actions Suppression.

alarm1 = nil # AWSCDK::CloudWatch::Alarm
alarm2 = nil # AWSCDK::CloudWatch::Alarm
on_alarm_action = nil # AWSCDK::CloudWatch::IAlarmAction
on_ok_action = nil # AWSCDK::CloudWatch::IAlarmAction
actions_suppressor = nil # AWSCDK::CloudWatch::Alarm


alarm_rule = AWSCDK::CloudWatch::AlarmRule.any_of(alarm1, alarm2)

my_composite_alarm = AWSCDK::CloudWatch::CompositeAlarm.new(self, "MyAwesomeCompositeAlarm", {
    alarm_rule: alarm_rule,
    actions_suppressor: actions_suppressor,
})
my_composite_alarm.add_alarm_action(on_alarm_action)
my_composite_alarm.add_ok_action(on_ok_action)

In the provided example, if actions_suppressor is in ALARM state, on_alarm_action won't be triggered even if my_composite_alarm goes into ALARM state. Similar, if actions_suppressor is in ALARM state and my_composite_alarm goes from ALARM into OK state, on_ok_action won't be triggered.

A note on units

In CloudWatch, Metrics datums are emitted with units, such as seconds or bytes. When Metric objects are given a unit attribute, it will be used to filter the stream of metric datums for datums emitted using the same unit attribute.

In particular, the unit field is not used to rescale datums or alarm threshold values (for example, it cannot be used to specify an alarm threshold in Megabytes if the metric stream is being emitted as bytes).

You almost certainly don't want to specify the unit property when creating Metric objects (which will retrieve all datums regardless of their unit), unless you have very specific requirements. Note that in any case, CloudWatch only supports filtering by unit for Alarms, not in Dashboard graphs.

Please see the following GitHub issue for a discussion on real unit calculations in CDK: https://github.com/aws/aws-cdk/issues/5595

Anomaly Detection Alarms

CloudWatch anomaly detection applies machine learning algorithms to create a model of expected metric behavior. You can use anomaly detection to:

Creating an Anomaly Detection Alarm

To build an Anomaly Detection Alarm, you should create a MathExpression that uses an ANOMALY_DETECTION_BAND() function, and use one of the band comparison operators (see the next section). Anomaly Detection Alarms have a dynamic threshold, not a fixed one, so the value for threshold is ignored. Specify the value 0 or use the symbolic Alarm.ANOMALY_DETECTION_NO_THRESHOLD value.

You can use the AnomalyDetectionAlarm class for convenience, which takes care of building the right metric math expression and passing in a magic value for the treshold for you:

# Create a metric
metric = AWSCDK::CloudWatch::Metric.new({
    namespace: "AWS/EC2",
    metric_name: "CPUUtilization",
    statistic: "Average",
    period: AWSCDK::Duration.hours(1),
})

# Create an anomaly detection alarm
alarm = AWSCDK::CloudWatch::AnomalyDetectionAlarm.new(self, "AnomalyAlarm", {
    metric: metric,
    evaluation_periods: 1,

    # Number of standard deviations for the band (default: 2)
    std_devs: 2,
    # Alarm outside on either side of the band, or just below or above it (default: outside)
    comparison_operator: AWSCDK::CloudWatch::ComparisonOperator::LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD,
    alarm_description: "Alarm when metric is outside the expected band",
})

Comparison Operators for Anomaly Detection

When creating an anomaly detection alarm, you must use one of the following comparison operators:

For more information on anomaly detection in CloudWatch, see the AWS documentation.

PromQL Alarms

PromQL alarms evaluate a PromQL instant query against metrics ingested through the CloudWatch OTLP endpoint on a recurring schedule. All matching time series returned by the query are considered breaching, and each is tracked independently as a contributor.

How PromQL Alarms Differ from Standard CloudWatch Alarms

The existing Alarm construct is designed around the standard CloudWatch alarm model: a metric, a comparison operator, a threshold, and evaluation periods. PromQL alarms have a fundamentally different configuration model:

Creating a PromQL Alarm

AWSCDK::CloudWatch::PromQLAlarm.new(self, "HighCpuAlarm", {
    alarm_name: "HighCpuAlarm",
    alarm_description: "Alarm when average CPU exceeds 80%",
    query: "avg(cpu_utilization_percent) > 80",
    evaluation_interval: AWSCDK::Duration.seconds(60),
})

Pending and Recovery Periods

Use pending_period to require a contributor to breach continuously for a duration before entering ALARM state (equivalent to Prometheus for duration). Use recovery_period to require a contributor to stop breaching for a duration before returning to OK state (equivalent to Prometheus keep_firing_for duration).

AWSCDK::CloudWatch::PromQLAlarm.new(self, "HighLatencyAlarm", {
    alarm_description: "P99 latency exceeds 500ms for 5 minutes",
    query: "histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m])) > 0.5",
    evaluation_interval: AWSCDK::Duration.seconds(60),
    pending_period: AWSCDK::Duration.seconds(300),
    recovery_period: AWSCDK::Duration.seconds(600),
})

Adding Actions

PromQLAlarm extends AlarmBase, so you can add alarm, OK, and insufficient-data actions the same way as standard alarms:

require 'aws-cdk-lib'

topic = nil # AWSCDK::SNS::Topic


alarm = AWSCDK::CloudWatch::PromQLAlarm.new(self, "ServiceDownAlarm", {
    query: "up == 0",
    evaluation_interval: AWSCDK::Duration.seconds(60),
    pending_period: AWSCDK::Duration.seconds(300),
    recovery_period: AWSCDK::Duration.seconds(300),
})

alarm.add_alarm_action(AWSCDK::CloudWatchActions::SNSAction.new(topic))
alarm.add_ok_action(AWSCDK::CloudWatchActions::SNSAction.new(topic))

Importing an Existing PromQL Alarm

imported_by_arn = AWSCDK::CloudWatch::PromQLAlarm.from_prom_ql_alarm_arn(self, "ImportedAlarm", "arn:aws:cloudwatch:us-east-1:123456789012:alarm:MyPromQLAlarm")

imported_by_name = AWSCDK::CloudWatch::PromQLAlarm.from_prom_ql_alarm_name(self, "ImportedByName", "MyPromQLAlarm")

Using in Composite Alarms

Since PromQLAlarm implements IAlarm, it can be used in composite alarm rules alongside standard alarms:

promql_alarm = nil # AWSCDK::CloudWatch::PromQLAlarm
standard_alarm = nil # AWSCDK::CloudWatch::Alarm


AWSCDK::CloudWatch::CompositeAlarm.new(self, "CompositeAlarm", {
    alarm_rule: AWSCDK::CloudWatch::AlarmRule.all_of(promql_alarm, standard_alarm),
})

Dashboards

Dashboards are set of Widgets stored server-side which can be accessed quickly from the AWS console. Available widgets are graphs of a metric over time, the current value of a metric, or a static piece of Markdown which explains what the graphs mean.

The following widgets are available:

Graph widget

A graph widget can display any number of metrics on either the left or right vertical axis:

dashboard = nil # AWSCDK::CloudWatch::Dashboard
execution_count_metric = nil # AWSCDK::CloudWatch::Metric
error_count_metric = nil # AWSCDK::CloudWatch::Metric


dashboard.add_widgets(AWSCDK::CloudWatch::GraphWidget.new({
    title: "Executions vs error rate",

    left: [execution_count_metric],

    right: [
        error_count_metric.with({
            statistic: AWSCDK::CloudWatch::Stats.AVERAGE,
            label: "Error rate",
            color: AWSCDK::CloudWatch::Color.GREEN,
        }),
    ],
}))

Using the methods add_left_metric() and add_right_metric() you can add metrics to a graph widget later on.

Graph widgets can also display annotations attached to the left or right y-axis or the x-axis.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::GraphWidget.new({
    # ...

    left_annotations: [
        {value: 1800, label: AWSCDK::Duration.minutes(30).to_human_string, color: AWSCDK::CloudWatch::Color.RED},
        {value: 3600, label: "1 hour", color: "#2ca02c"},
    ],
    vertical_annotations: [
        {date: "2022-10-19T00:00:00Z", label: "Deployment", color: AWSCDK::CloudWatch::Color.RED},
    ],
}))

The graph legend can be adjusted from the default position at bottom of the widget.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::GraphWidget.new({
    # ...

    legend_position: AWSCDK::CloudWatch::LegendPosition::RIGHT,
}))

The graph can publish live data within the last minute that has not been fully aggregated.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::GraphWidget.new({
    # ...

    live_data: true,
}))

The graph view can be changed from default 'timeSeries' to 'bar' or 'pie'.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::GraphWidget.new({
    # ...

    view: AWSCDK::CloudWatch::GraphWidgetView::BAR,
}))

The display_labels_on_chart property can be set to true to show labels on the chart. Note that this only has an effect when the view property is set to cloudwatch.GraphWidgetView.PIE.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::GraphWidget.new({
    # ...

    view: AWSCDK::CloudWatch::GraphWidgetView::PIE,
    display_labels_on_chart: true,
}))

The start and end properties can be used to specify the time range for each graph widget independently from those of the dashboard. The parameters can be specified at GraphWidget, GaugeWidget, and SingleValueWidget.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::GraphWidget.new({
    # ...

    start: "-P7D",
    _end: "2018-12-17T06:00:00.000Z",
}))

Table Widget

A TableWidget can display any number of metrics in tabular form.

dashboard = nil # AWSCDK::CloudWatch::Dashboard
execution_count_metric = nil # AWSCDK::CloudWatch::Metric


dashboard.add_widgets(AWSCDK::CloudWatch::TableWidget.new({
    title: "Executions",
    metrics: [execution_count_metric],
}))

The layout property can be used to invert the rows and columns of the table. The default cloudwatch.TableLayout.HORIZONTAL means that metrics are shown in rows and datapoints in columns. cloudwatch.TableLayout.VERTICAL means that metrics are shown in columns and datapoints in rows.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::TableWidget.new({
    # ...

    layout: AWSCDK::CloudWatch::TableLayout::VERTICAL,
}))

The summary property allows customizing the table to show summary columns (columns sub property), whether to make the summary columns sticky remaining in view while scrolling (sticky sub property), and to optionally only present summary columns (hide_non_summary_columns sub property).

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::TableWidget.new({
    # ...

    summary: {
        columns: [AWSCDK::CloudWatch::TableSummaryColumn::AVERAGE],
        hide_non_summary_columns: true,
        sticky: true,
    },
}))

The thresholds property can be used to highlight cells with a color when the datapoint value falls within the threshold.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::TableWidget.new({
    # ...

    thresholds: [
        AWSCDK::CloudWatch::TableThreshold.above(1000, AWSCDK::CloudWatch::Color.RED),
        AWSCDK::CloudWatch::TableThreshold.between(500, 1000, AWSCDK::CloudWatch::Color.ORANGE),
        AWSCDK::CloudWatch::TableThreshold.below(500, AWSCDK::CloudWatch::Color.GREEN),
    ],
}))

The show_units_in_label property can be used to display what unit is associated with a metric in the label column.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::TableWidget.new({
    # ...

    show_units_in_label: true,
}))

The full_precision property can be used to show as many digits as can fit in a cell, before rounding.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::TableWidget.new({
    # ...

    full_precision: true,
}))

Gauge widget

Gauge graph requires the max and min value of the left Y axis, if no value is informed the limits will be from 0 to 100.

dashboard = nil # AWSCDK::CloudWatch::Dashboard
error_alarm = nil # AWSCDK::CloudWatch::Alarm
gauge_metric = nil # AWSCDK::CloudWatch::Metric


dashboard.add_widgets(AWSCDK::CloudWatch::GaugeWidget.new({
    metrics: [gauge_metric],
    left_y_axis: {
        min: 0,
        max: 1000,
    },
}))

Alarm widget

An alarm widget shows the graph and the alarm line of a single alarm:

dashboard = nil # AWSCDK::CloudWatch::Dashboard
error_alarm = nil # AWSCDK::CloudWatch::Alarm


dashboard.add_widgets(AWSCDK::CloudWatch::AlarmWidget.new({
    title: "Errors",
    alarm: error_alarm,
}))

Single value widget

A single-value widget shows the latest value of a set of metrics (as opposed to a graph of the value over time):

dashboard = nil # AWSCDK::CloudWatch::Dashboard
visitor_count = nil # AWSCDK::CloudWatch::Metric
purchase_count = nil # AWSCDK::CloudWatch::Metric


dashboard.add_widgets(AWSCDK::CloudWatch::SingleValueWidget.new({
    metrics: [visitor_count, purchase_count],
}))

Show as many digits as can fit, before rounding.

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::SingleValueWidget.new({
    metrics: [],

    full_precision: true,
}))

Sparkline allows you to glance the trend of a metric by displaying a simplified linegraph below the value. You can't use sparkline: true together with setPeriodToTimeRange: true

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::SingleValueWidget.new({
    metrics: [],

    sparkline: true,
}))

Period allows you to set the default period for the widget:

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::SingleValueWidget.new({
    metrics: [],

    period: AWSCDK::Duration.minutes(15),
}))

Text widget

A text widget shows an arbitrary piece of MarkDown. Use this to add explanations to your dashboard:

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::TextWidget.new({
    markdown: "# Key Performance Indicators",
}))

Optionally set the TextWidget background to be transparent

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::TextWidget.new({
    markdown: "# Key Performance Indicators",
    background: AWSCDK::CloudWatch::TextWidgetBackground::TRANSPARENT,
}))

Alarm Status widget

An alarm status widget displays instantly the status of any type of alarms and gives the ability to aggregate one or more alarms together in a small surface.

dashboard = nil # AWSCDK::CloudWatch::Dashboard
error_alarm = nil # AWSCDK::CloudWatch::Alarm


dashboard.add_widgets(
AWSCDK::CloudWatch::AlarmStatusWidget.new({
    alarms: [error_alarm],
}))

An alarm status widget only showing firing alarms, sorted by state and timestamp:

dashboard = nil # AWSCDK::CloudWatch::Dashboard
error_alarm = nil # AWSCDK::CloudWatch::Alarm


dashboard.add_widgets(AWSCDK::CloudWatch::AlarmStatusWidget.new({
    title: "Errors",
    alarms: [error_alarm],
    sort_by: AWSCDK::CloudWatch::AlarmStatusWidgetSortBy::STATE_UPDATED_TIMESTAMP,
    states: [AWSCDK::CloudWatch::AlarmState::ALARM],
}))

Query results widget

A LogQueryWidget shows the results of a query from Logs Insights:

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::LogQueryWidget.new({
    log_group_names: ["my-log-group"],
    view: AWSCDK::CloudWatch::LogQueryVisualizationType::TABLE,
    # The lines will be automatically combined using '\n|'.
    query_lines: [
        "fields @message",
        "filter @message like /Error/",
    ],
}))

Log Insights QL is the default query language. You may specify an alternate query language: OpenSearch PPL or SQL, if desired:

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::LogQueryWidget.new({
    log_group_names: ["my-log-group"],
    view: AWSCDK::CloudWatch::LogQueryVisualizationType::TABLE,
    query_string: "SELECT count(*) as count FROM 'my-log-group'",
    query_language: AWSCDK::CloudWatch::LogQueryLanguage::SQL,
}))

Custom widget

A CustomWidget shows the result of an AWS Lambda function:

dashboard = nil # AWSCDK::CloudWatch::Dashboard


# Import or create a lambda function
fn = AWSCDK::Lambda::Function.from_function_arn(dashboard, "Function", "arn:aws:lambda:us-east-1:123456789012:function:MyFn")

dashboard.add_widgets(AWSCDK::CloudWatch::CustomWidget.new({
    function_arn: fn.function_arn,
    title: "My lambda baked widget",
}))

You can learn more about custom widgets in the Amazon Cloudwatch User Guide.

Dashboard Layout

The widgets on a dashboard are visually laid out in a grid that is 24 columns wide. Normally you specify X and Y coordinates for the widgets on a Dashboard, but because this is inconvenient to do manually, the library contains a simple layout system to help you lay out your dashboards the way you want them to.

Widgets have a width and height property, and they will be automatically laid out either horizontally or vertically stacked to fill out the available space.

Widgets are added to a Dashboard by calling add(widget1, widget2, ...). Widgets given in the same call will be laid out horizontally. Widgets given in different calls will be laid out vertically. To make more complex layouts, you can use the following widgets to pack widgets together in different ways:

Column widget

A column widget contains other widgets and they will be laid out in a vertical column. Widgets will be put one after another in order.

widget_a = nil # AWSCDK::CloudWatch::IWidget
widget_b = nil # AWSCDK::CloudWatch::IWidget


AWSCDK::CloudWatch::Column.new(widget_a, widget_b)

You can add a widget after object instantiation with the method add_widget(). Each new widget will be put at the bottom of the column.

Row widget

A row widget contains other widgets and they will be laid out in a horizontal row. Widgets will be put one after another in order. If the total width of the row exceeds the max width of the grid of 24 columns, the row will wrap automatically and adapt its height.

widget_a = nil # AWSCDK::CloudWatch::IWidget
widget_b = nil # AWSCDK::CloudWatch::IWidget


AWSCDK::CloudWatch::Row.new(widget_a, widget_b)

You can add a widget after object instantiation with the method add_widget().

Interval duration for dashboard

Interval duration for metrics in dashboard. You can specify default_interval with the relative time (e.g. 7 days) as Duration.days(7).

require 'aws-cdk-lib'


dashboard = AWSCDK::CloudWatch::Dashboard.new(self, "Dash", {
    default_interval: AWSCDK::Duration.days(7),
})

Here, the dashboard would show the metrics for the last 7 days.

Dashboard variables

Dashboard variables are a convenient way to create flexible dashboards that display different content depending on the value of an input field within a dashboard. They create a dashboard on which it's possible to quickly switch between different Lambda functions, Amazon EC2 instances, etc.

You can learn more about Dashboard variables in the Amazon Cloudwatch User Guide

There are two types of dashboard variables available: a property variable and a pattern variable.

A use case of a property variable is a dashboard with the ability to toggle the region property to see the same dashboard in different regions:

require 'aws-cdk-lib'


dashboard = AWSCDK::CloudWatch::Dashboard.new(self, "Dash", {
    default_interval: AWSCDK::Duration.days(7),
    variables: [
        AWSCDK::CloudWatch::DashboardVariable.new({
            id: "region",
            type: AWSCDK::CloudWatch::VariableType::PROPERTY,
            label: "Region",
            input_type: AWSCDK::CloudWatch::VariableInputType::RADIO,
            value: "region",
            values: AWSCDK::CloudWatch::Values.from_values({label: "IAD", value: "us-east-1"}, {label: "DUB", value: "us-west-2"}),
            default_value: AWSCDK::CloudWatch::DefaultValue.value("us-east-1"),
            visible: true,
        }),
    ],
})

This example shows how to change region everywhere, assuming the current dashboard is showing region us-east-1 already, by using pattern variable

require 'aws-cdk-lib'


dashboard = AWSCDK::CloudWatch::Dashboard.new(self, "Dash", {
    default_interval: AWSCDK::Duration.days(7),
    variables: [
        AWSCDK::CloudWatch::DashboardVariable.new({
            id: "region2",
            type: AWSCDK::CloudWatch::VariableType::PATTERN,
            label: "RegionPattern",
            input_type: AWSCDK::CloudWatch::VariableInputType::INPUT,
            value: "us-east-1",
            default_value: AWSCDK::CloudWatch::DefaultValue.value("us-east-1"),
            visible: true,
        }),
    ],
})

The following example generates a Lambda function variable, with a radio button for each function. Functions are discovered by a metric query search. The values with cw.Values.fromSearchComponents indicates that the values will be populated from FunctionName values retrieved from the search expression {AWS/Lambda,FunctionName} MetricName=\"Duration\". The default_value with cw.DefaultValue.FIRST indicates that the default value will be the first value returned from the search.

require 'aws-cdk-lib'


dashboard = AWSCDK::CloudWatch::Dashboard.new(self, "Dash", {
    default_interval: AWSCDK::Duration.days(7),
    variables: [
        AWSCDK::CloudWatch::DashboardVariable.new({
            id: "functionName",
            type: AWSCDK::CloudWatch::VariableType::PATTERN,
            label: "Function",
            input_type: AWSCDK::CloudWatch::VariableInputType::RADIO,
            value: "originalFuncNameInDashboard",
            # equivalent to cw.Values.fromSearch('{AWS/Lambda,FunctionName} MetricName=\"Duration\"', 'FunctionName')
            values: AWSCDK::CloudWatch::Values.from_search_components({
                namespace: "AWS/Lambda",
                dimensions: ["FunctionName"],
                metric_name: "Duration",
                populate_from: "FunctionName",
            }),
            default_value: AWSCDK::CloudWatch::DefaultValue.FIRST,
            visible: true,
        }),
    ],
})

You can add a variable after object instantiation with the method dashboard.addVariable().

Cross-Account Visibility

Both Log and Metric Widget objects support cross-account visibility by allowing you to specify the AWS Account ID that the data (logs or metrics) originates from.

Prerequisites:

  1. The monitoring account must be set up as a monitoring account
  2. The source account must grant permissions to the monitoring account
  3. Appropriate IAM roles and policies must be configured

For detailed setup instructions, see Cross-Account Cross-Region CloudWatch Console.

To use this feature, you can set the account_id property on LogQueryWidget, GraphWidget, AlarmWidget, SingleValueWidget, and GaugeWidget constructs:

dashboard = nil # AWSCDK::CloudWatch::Dashboard


dashboard.add_widgets(AWSCDK::CloudWatch::GraphWidget.new({
    # ...
    account_id: "123456789012",
}))

dashboard.add_widgets(AWSCDK::CloudWatch::LogQueryWidget.new({
    log_group_names: ["my-log-group"],
    # ...
    account_id: "123456789012",
    query_lines: [
        "fields @message",
    ],
}))

API Reference

Classes 38

AlarmAn alarm on a CloudWatch metric. AlarmBaseThe base class for Alarm and CompositeAlarm resources. AlarmRuleClass with static functions to build AlarmRule for Composite Alarms. AlarmStatusWidgetA dashboard widget that displays alarms in a grid view. AlarmWidgetDisplay the metric associated with an alarm, including the alarm line. AnomalyDetectionAlarmCloudWatch Alarm that uses anomaly detection to trigger alarms. CfnAlarmThe `AWS::CloudWatch::Alarm` type specifies an alarm and associates it with the specified CfnAlarmMuteRuleResource Type definition for AWS::CloudWatch::AlarmMuteRule that allows defining a rule an CfnAnomalyDetectorThe `AWS::CloudWatch::AnomalyDetector` type specifies an anomaly detection band for a cert CfnCompositeAlarmThe `AWS::CloudWatch::CompositeAlarm` type creates or updates a composite alarm. CfnDashboardThe `AWS::CloudWatch::Dashboard` resource specifies an Amazon CloudWatch dashboard. CfnInsightRuleCreates or updates a Contributor Insights rule. CfnLogAlarmResource Type definition for AWS::CloudWatch::LogAlarm. CfnMetricStreamCreates or updates a metric stream. CfnOTelEnrichmentAWS::CloudWatch::OTelEnrichment enables OTel metric enrichment in CloudWatch, allowing Clo ColorA set of standard colours that can be used in annotations in a GraphWidget. ColumnA widget that contains other widgets in a vertical column. CompositeAlarmA Composite Alarm based on Alarm Rule. ConcreteWidgetA real CloudWatch widget that has its own fixed size and remembers its position. CustomWidgetA CustomWidget shows the result of a AWS lambda function. DashboardA CloudWatch dashboard. DashboardVariableDashboard Variable. DefaultValueDefault value for use in {@link DashboardVariableOptions}. GaugeWidgetA dashboard gauge widget that displays metrics. GraphWidgetA dashboard widget that displays metrics. LogQueryWidgetDisplay query results from Logs Insights. MathExpressionA math expression built with metric(s) emitted by a service. MetricA metric emitted by a service. PromQLAlarmA CloudWatch Alarm based on a PromQL query expression. RowA widget that contains other widgets in a horizontal row. SearchExpressionA CloudWatch search expression for dynamically finding and graphing multiple related metri SingleValueWidgetA dashboard widget that displays the most recent value for every metric. SpacerA widget that doesn't display anything but takes up space. StatsFactory functions for standard statistics strings. TableThresholdThresholds for highlighting cells in TableWidget. TableWidgetA dashboard widget that displays metrics. TextWidgetA dashboard widget that displays MarkDown. ValuesA class for providing values for use with {@link VariableInputType.SELECT} and {@link Vari

Interfaces 52

AlarmActionConfigProperties for an alarm action. AlarmPropsProperties for Alarms. AlarmStatusWidgetPropsProperties for an Alarm Status Widget. AlarmWidgetPropsProperties for an AlarmWidget. AnomalyDetectionAlarmPropsProperties for Anomaly Detection Alarms. AnomalyDetectionMetricOptionsProperties needed to make an anomaly detection alarm from a metric. CfnAlarmMuteRulePropsProperties for defining a `CfnAlarmMuteRule`. CfnAlarmPropsProperties for defining a `CfnAlarm`. CfnAnomalyDetectorPropsProperties for defining a `CfnAnomalyDetector`. CfnCompositeAlarmPropsProperties for defining a `CfnCompositeAlarm`. CfnDashboardPropsProperties for defining a `CfnDashboard`. CfnInsightRulePropsProperties for defining a `CfnInsightRule`. CfnLogAlarmPropsProperties for defining a `CfnLogAlarm`. CfnMetricStreamPropsProperties for defining a `CfnMetricStream`. CfnOTelEnrichmentPropsProperties for defining a `CfnOTelEnrichment`. CommonMetricOptionsOptions shared by most methods accepting metric options. CompositeAlarmPropsProperties for creating a Composite Alarm. CreateAlarmOptionsProperties needed to make an alarm from a metric. CustomWidgetPropsThe properties for a CustomWidget. DashboardPropsProperties for defining a CloudWatch Dashboard. DashboardVariableOptionsOptions for {@link DashboardVariable}. DimensionMetric dimension. GaugeWidgetPropsProperties for a GaugeWidget. GraphWidgetPropsProperties for a GraphWidget. HorizontalAnnotationHorizontal annotation to be added to a graph. IAlarmRepresents a CloudWatch Alarm. IAlarmActionInterface for objects that can be the targets of CloudWatch alarm actions. IAlarmRuleInterface for Alarm Rule. IMetricInterface for metrics. IVariableA single dashboard variable. IWidgetA single dashboard widget. LogQueryWidgetPropsProperties for a Query widget. MathExpressionOptionsConfigurable options for MathExpressions. MathExpressionPropsProperties for a MathExpression. MetricConfigProperties of a rendered metric. MetricExpressionConfigProperties for a concrete metric. MetricOptionsProperties of a metric that can be changed. MetricPropsProperties for a metric. MetricStatConfigProperties for a concrete metric. MetricWidgetPropsBasic properties for widgets that display metrics. PromQLAlarmPropsProperties for creating a PromQL Alarm. SearchComponentsSearch components for use with {@link Values.fromSearchComponents}. SearchExpressionOptionsConfigurable options for SearchExpressions. SearchExpressionPropsProperties for a SearchExpression. SingleValueWidgetPropsProperties for a SingleValueWidget. SpacerPropsProps of the spacer. TableSummaryPropsProperties for TableWidget's summary columns. TableWidgetPropsProperties for a TableWidget. TextWidgetPropsProperties for a Text widget. VariableValue VerticalAnnotationVertical annotation to be added to a graph. YAxisPropsProperties for a Y-Axis.

Enums 18

AlarmStateEnumeration indicates state of Alarm used in building Alarm Rule. AlarmStatusWidgetSortByThe sort possibilities for AlarmStatusWidgets. ComparisonOperatorComparison operator for evaluating alarms. GraphWidgetViewTypes of view. LegendPositionThe position of the legend on a GraphWidget. LogQueryLanguageLogs Query Language. LogQueryVisualizationTypeTypes of view. PeriodOverrideSpecify the period for graphs when the CloudWatch dashboard loads. ShadingFill shading options that will be used with a horizontal annotation. StatisticStatistic to use over the aggregation period. TableLayoutLayout for TableWidget. TableSummaryColumnStandard table summary columns. TextWidgetBackgroundBackground types available. TreatMissingDataSpecify how missing data points are treated during alarm evaluation. UnitUnit for metric. VariableInputType VariableType VerticalShadingFill shading options that will be used with a vertical annotation.