Package software.amazon.awscdk.services.cloudwatch
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 metricXxx() 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:
Function fn; Metric errors = fn.metricErrors();
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:
HostedZone hostedZone = HostedZone.Builder.create(this, "MyHostedZone").zoneName("example.org").build();
Metric metric = Metric.Builder.create()
.namespace("AWS/Route53")
.metricName("DNSQueries")
.dimensionsMap(Map.of(
"HostedZoneId", hostedZone.getHostedZoneId()))
.build();
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 metric = Metric.Builder.create()
.namespace("MyNamespace")
.metricName("MyMetric")
.dimensionsMap(Map.of(
"ProcessingStep", "Download"))
.build();
Metric ID
Metrics can be assigned a unique identifier using the id property. This is
useful when referencing metrics in math expressions:
Metric metric = Metric.Builder.create()
.namespace("AWS/Lambda")
.metricName("Invocations")
.dimensionsMap(Map.of(
"FunctionName", "MyFunction"))
.id("invocations")
.build();
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:
Function fn;
Metric metric = fn.metricErrors(MetricOptions.builder()
.visible(false)
.build());
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:
Function fn;
MathExpression allProblems = MathExpression.Builder.create()
.expression("errors + throttles")
.usingMetrics(Map.of(
"errors", fn.metricErrors(),
"throttles", fn.metricThrottles()))
.build();
You can use MathExpression objects like any other metric, including using
them in other math expressions:
Function fn;
MathExpression allProblems;
MathExpression problemPercentage = MathExpression.Builder.create()
.expression("(problems / invocations) * 100")
.usingMetrics(Map.of(
"problems", allProblems,
"invocations", fn.metricInvocations()))
.build();
Metric ID Usage in Math Expressions
When metrics have custom IDs, you can reference them directly in math expressions.
Function fn;
Metric invocations = fn.metricInvocations(MetricOptions.builder()
.id("lambda_invocations")
.build());
Metric errors = fn.metricErrors(MetricOptions.builder()
.id("lambda_errors")
.build());
When metrics have predefined IDs, they can be referenced directly in math expressions by their ID without requiring the usingMetrics property.
MathExpression errorRate = MathExpression.Builder.create()
.expression("lambda_errors / lambda_invocations * 100")
.label("Error Rate (%)")
.build();
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:
SearchExpression cpuUtilization = SearchExpression.Builder.create()
.expression("SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 900)")
.label("EC2 CPU Utilization")
.color("#ff7f0e")
.build();
Cross-account and cross-region search expressions are also supported. Use
the searchAccount and searchRegion properties to specify the account
and/or region to evaluate the search expression against.
SearchExpression crossAccountSearch = SearchExpression.Builder.create()
.expression("SEARCH('{AWS/Lambda,FunctionName} MetricName=\"Invocations\"', 'Sum', 300)")
.searchAccount("123456789012")
.searchRegion("us-west-2")
.label("Production Lambda Invocations")
.build();
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:
Function fn;
Metric minuteErrorRate = fn.metricErrors(MetricOptions.builder()
.statistic(Stats.AVERAGE)
.period(Duration.minutes(1))
.label("Lambda failure rate")
.build());
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 metricErrors 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
Sumto count discrete events is that some events are emitted as either0or1(for exampleErrorsfor a Lambda) and some are only emitted as1(for exampleNumberOfMessagesPublishedfor an SNS topic).In case
0-metrics are emitted, it makes sense to take theAverageof this metric: the result will be the fraction of errors over all executions.If
0-metrics are not emitted, theAveragewill always be equal to1, and not be very useful.In order to simplify the mental model of
Metricobjects, we default to aggregating usingSum, 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%) \| WM(x%:) \| WM(:y%) | Stats.wm(10, 90) |
| Trimmed count (TC) | tc99 = TC(:99%) | TC(x:y) \| TC(x%:y%) \| TC(x%:) \| TC(:y%) | Stats.tc(10, 90) |
| Trimmed sum (TS) | ts99 = TS(:99%) | TS(x:y) \| TS(x%:y%) \| TS(x%:) \| TS(:y%) | Stats.ts(10, 90) |
| Percentile rank (PR) | ❌ | PR(x:y) \| PR(x:) \| PR(:y) | Stats.pr(10, 5000) |
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.
HostedZone hostedZone;
Metric.Builder.create()
.namespace("AWS/Route53")
.metricName("DNSQueries")
.dimensionsMap(Map.of(
"HostedZoneId", hostedZone.getHostedZoneId()))
.statistic(Stats.SAMPLE_COUNT)
.period(Duration.minutes(5))
.build();
Metric.Builder.create()
.namespace("AWS/Route53")
.metricName("DNSQueries")
.dimensionsMap(Map.of(
"HostedZoneId", hostedZone.getHostedZoneId()))
.statistic(Stats.p(99))
.period(Duration.minutes(5))
.build();
Metric.Builder.create()
.namespace("AWS/Route53")
.metricName("DNSQueries")
.dimensionsMap(Map.of(
"HostedZoneId", hostedZone.getHostedZoneId()))
.statistic("TS(7.5%:90%)")
.period(Duration.minutes(5))
.build();
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:
Function fn;
Metric minuteErrorRate = fn.metricErrors(MetricOptions.builder()
.statistic(Stats.SUM)
.period(Duration.hours(1))
// Show the maximum hourly error count in the legend
.label("[max: ${MAX}] Lambda failure rate")
.build());
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:
Function fn;
Alarm.Builder.create(this, "Alarm")
.metric(fn.metricErrors())
.threshold(100)
.evaluationPeriods(2)
.build();
Alternatively, you can call metric.createAlarm():
Function fn;
fn.metricErrors().createAlarm(this, "Alarm", CreateAlarmOptions.builder()
.threshold(100)
.evaluationPeriods(2)
.build());
The most important properties to set while creating an Alarms are:
threshold: the value to compare the metric against.comparisonOperator: the comparison operation to use, defaults tometric >= threshold.evaluationPeriods: how many consecutive periods the metric has to be breaching the threshold for the alarm to trigger.
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:
- Create a cross-Account alarm that has
evaluateLowSampleCountPercentile: "ignore". The reason is that the only way to pass an AccountID is to use theMetricsfield of the Alarm resource. If we use theMetricsfield, the CloudWatch event that is used to evaluate the Alarm doesn't have aSampleCountfield anymore ("When CloudWatch evaluates alarms, periods are aggregated into single data points"). The result is that the Alarm cannot evaluate at all. - Create a cross-Region alarm (source).
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:
import software.amazon.awscdk.services.cloudwatch.actions.*; Alarm alarm; Topic topic = new Topic(this, "Topic"); alarm.addAlarmAction(new SnsAction(topic));
Notification formats
Alarms can be created in one of two "formats":
- With "top-level parameters" (these are the classic style of CloudWatch Alarms).
- With a list of metrics specifications (these are the modern style of CloudWatch Alarms).
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:
- Metric math
- Cross-account metrics
- Labels
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.
Alarm alarm1;
Alarm alarm2;
Alarm alarm3;
Alarm alarm4;
IAlarmRule alarmRule = AlarmRule.anyOf(AlarmRule.allOf(AlarmRule.anyOf(alarm1, AlarmRule.fromAlarm(alarm2, AlarmState.OK), alarm3), AlarmRule.not(AlarmRule.fromAlarm(alarm4, AlarmState.INSUFFICIENT_DATA))), AlarmRule.fromBoolean(false));
CompositeAlarm.Builder.create(this, "MyAwesomeCompositeAlarm")
.alarmRule(alarmRule)
.build();
Actions Suppressor
If you want to disable actions of a Composite Alarm based on a certain condition, you can use Actions Suppression.
Alarm alarm1;
Alarm alarm2;
IAlarmAction onAlarmAction;
IAlarmAction onOkAction;
Alarm actionsSuppressor;
IAlarmRule alarmRule = AlarmRule.anyOf(alarm1, alarm2);
CompositeAlarm myCompositeAlarm = CompositeAlarm.Builder.create(this, "MyAwesomeCompositeAlarm")
.alarmRule(alarmRule)
.actionsSuppressor(actionsSuppressor)
.build();
myCompositeAlarm.addAlarmAction(onAlarmAction);
myCompositeAlarm.addOkAction(onOkAction);
In the provided example, if actionsSuppressor is in ALARM state, onAlarmAction won't be triggered even if myCompositeAlarm goes into ALARM state.
Similar, if actionsSuppressor is in ALARM state and myCompositeAlarm goes from ALARM into OK state, onOkAction 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:
- Detect anomalies with minimal configuration
- Visualize expected metric behavior
- Create alarms that trigger when metrics deviate from expected patterns
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 metric = Metric.Builder.create()
.namespace("AWS/EC2")
.metricName("CPUUtilization")
.statistic("Average")
.period(Duration.hours(1))
.build();
// Create an anomaly detection alarm
AnomalyDetectionAlarm alarm = AnomalyDetectionAlarm.Builder.create(this, "AnomalyAlarm")
.metric(metric)
.evaluationPeriods(1)
// Number of standard deviations for the band (default: 2)
.stdDevs(2)
// Alarm outside on either side of the band, or just below or above it (default: outside)
.comparisonOperator(ComparisonOperator.LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD)
.alarmDescription("Alarm when metric is outside the expected band")
.build();
Comparison Operators for Anomaly Detection
When creating an anomaly detection alarm, you must use one of the following comparison operators:
LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD: Alarm when the metric is outside the band, on either side of itGREATER_THAN_UPPER_THRESHOLD: Alarm only when the metric is above the bandLESS_THAN_LOWER_THRESHOLD: Alarm only when the metric is below the band
For more information on anomaly detection in CloudWatch, see the AWS documentation.
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:
GraphWidget-- shows any number of metrics on both the left and right vertical axes.AlarmWidget-- shows the graph and alarm line for a single alarm.SingleValueWidget-- shows the current value of a set of metrics.TextWidget-- shows some static Markdown.AlarmStatusWidget-- shows the status of your alarms in a grid view.
Graph widget
A graph widget can display any number of metrics on either the left or
right vertical axis:
Dashboard dashboard;
Metric executionCountMetric;
Metric errorCountMetric;
dashboard.addWidgets(GraphWidget.Builder.create()
.title("Executions vs error rate")
.left(List.of(executionCountMetric))
.right(List.of(errorCountMetric.with(MetricOptions.builder()
.statistic(Stats.AVERAGE)
.label("Error rate")
.color(Color.GREEN)
.build())))
.build());
Using the methods addLeftMetric() and addRightMetric() 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 dashboard;
dashboard.addWidgets(GraphWidget.Builder.create()
// ...
.leftAnnotations(List.of(HorizontalAnnotation.builder().value(1800).label(Duration.minutes(30).toHumanString()).color(Color.RED).build(), HorizontalAnnotation.builder().value(3600).label("1 hour").color("#2ca02c").build()))
.verticalAnnotations(List.of(VerticalAnnotation.builder().date("2022-10-19T00:00:00Z").label("Deployment").color(Color.RED).build()))
.build());
The graph legend can be adjusted from the default position at bottom of the widget.
Dashboard dashboard;
dashboard.addWidgets(GraphWidget.Builder.create()
// ...
.legendPosition(LegendPosition.RIGHT)
.build());
The graph can publish live data within the last minute that has not been fully aggregated.
Dashboard dashboard;
dashboard.addWidgets(GraphWidget.Builder.create()
// ...
.liveData(true)
.build());
The graph view can be changed from default 'timeSeries' to 'bar' or 'pie'.
Dashboard dashboard;
dashboard.addWidgets(GraphWidget.Builder.create()
// ...
.view(GraphWidgetView.BAR)
.build());
The displayLabelsOnChart 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 dashboard;
dashboard.addWidgets(GraphWidget.Builder.create()
// ...
.view(GraphWidgetView.PIE)
.displayLabelsOnChart(true)
.build());
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 dashboard;
dashboard.addWidgets(GraphWidget.Builder.create()
// ...
.start("-P7D")
.end("2018-12-17T06:00:00.000Z")
.build());
Table Widget
A TableWidget can display any number of metrics in tabular form.
Dashboard dashboard;
Metric executionCountMetric;
dashboard.addWidgets(TableWidget.Builder.create()
.title("Executions")
.metrics(List.of(executionCountMetric))
.build());
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 dashboard;
dashboard.addWidgets(TableWidget.Builder.create()
// ...
.layout(TableLayout.VERTICAL)
.build());
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 (hideNonSummaryColumns sub property).
Dashboard dashboard;
dashboard.addWidgets(TableWidget.Builder.create()
// ...
.summary(TableSummaryProps.builder()
.columns(List.of(TableSummaryColumn.AVERAGE))
.hideNonSummaryColumns(true)
.sticky(true)
.build())
.build());
The thresholds property can be used to highlight cells with a color when the datapoint value falls within the threshold.
Dashboard dashboard;
dashboard.addWidgets(TableWidget.Builder.create()
// ...
.thresholds(List.of(TableThreshold.above(1000, Color.RED), TableThreshold.between(500, 1000, Color.ORANGE), TableThreshold.below(500, Color.GREEN)))
.build());
The showUnitsInLabel property can be used to display what unit is associated with a metric in the label column.
Dashboard dashboard;
dashboard.addWidgets(TableWidget.Builder.create()
// ...
.showUnitsInLabel(true)
.build());
The fullPrecision property can be used to show as many digits as can fit in a cell, before rounding.
Dashboard dashboard;
dashboard.addWidgets(TableWidget.Builder.create()
// ...
.fullPrecision(true)
.build());
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 dashboard;
Alarm errorAlarm;
Metric gaugeMetric;
dashboard.addWidgets(GaugeWidget.Builder.create()
.metrics(List.of(gaugeMetric))
.leftYAxis(YAxisProps.builder()
.min(0)
.max(1000)
.build())
.build());
Alarm widget
An alarm widget shows the graph and the alarm line of a single alarm:
Dashboard dashboard;
Alarm errorAlarm;
dashboard.addWidgets(AlarmWidget.Builder.create()
.title("Errors")
.alarm(errorAlarm)
.build());
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 dashboard;
Metric visitorCount;
Metric purchaseCount;
dashboard.addWidgets(SingleValueWidget.Builder.create()
.metrics(List.of(visitorCount, purchaseCount))
.build());
Show as many digits as can fit, before rounding.
Dashboard dashboard;
dashboard.addWidgets(SingleValueWidget.Builder.create()
.metrics(List.of())
.fullPrecision(true)
.build());
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 dashboard;
dashboard.addWidgets(SingleValueWidget.Builder.create()
.metrics(List.of())
.sparkline(true)
.build());
Period allows you to set the default period for the widget:
Dashboard dashboard;
dashboard.addWidgets(SingleValueWidget.Builder.create()
.metrics(List.of())
.period(Duration.minutes(15))
.build());
Text widget
A text widget shows an arbitrary piece of MarkDown. Use this to add explanations to your dashboard:
Dashboard dashboard;
dashboard.addWidgets(TextWidget.Builder.create()
.markdown("# Key Performance Indicators")
.build());
Optionally set the TextWidget background to be transparent
Dashboard dashboard;
dashboard.addWidgets(TextWidget.Builder.create()
.markdown("# Key Performance Indicators")
.background(TextWidgetBackground.TRANSPARENT)
.build());
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 dashboard;
Alarm errorAlarm;
dashboard.addWidgets(
AlarmStatusWidget.Builder.create()
.alarms(List.of(errorAlarm))
.build());
An alarm status widget only showing firing alarms, sorted by state and timestamp:
Dashboard dashboard;
Alarm errorAlarm;
dashboard.addWidgets(AlarmStatusWidget.Builder.create()
.title("Errors")
.alarms(List.of(errorAlarm))
.sortBy(AlarmStatusWidgetSortBy.STATE_UPDATED_TIMESTAMP)
.states(List.of(AlarmState.ALARM))
.build());
Query results widget
A LogQueryWidget shows the results of a query from Logs Insights:
Dashboard dashboard;
dashboard.addWidgets(LogQueryWidget.Builder.create()
.logGroupNames(List.of("my-log-group"))
.view(LogQueryVisualizationType.TABLE)
// The lines will be automatically combined using '\n|'.
.queryLines(List.of("fields @message", "filter @message like /Error/"))
.build());
Log Insights QL is the default query language. You may specify an alternate query language: OpenSearch PPL or SQL, if desired:
Dashboard dashboard;
dashboard.addWidgets(LogQueryWidget.Builder.create()
.logGroupNames(List.of("my-log-group"))
.view(LogQueryVisualizationType.TABLE)
.queryString("SELECT count(*) as count FROM 'my-log-group'")
.queryLanguage(LogQueryLanguage.SQL)
.build());
Custom widget
A CustomWidget shows the result of an AWS Lambda function:
Dashboard dashboard;
// Import or create a lambda function
IFunction fn = Function.fromFunctionArn(dashboard, "Function", "arn:aws:lambda:us-east-1:123456789012:function:MyFn");
dashboard.addWidgets(CustomWidget.Builder.create()
.functionArn(fn.getFunctionArn())
.title("My lambda baked widget")
.build());
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: stack two or more widgets vertically.Row: lay out two or more widgets horizontally.Spacer: take up empty space
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.
IWidget widgetA; IWidget widgetB; new Column(widgetA, widgetB);
You can add a widget after object instantiation with the method
addWidget(). 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.
IWidget widgetA; IWidget widgetB; new Row(widgetA, widgetB);
You can add a widget after object instantiation with the method
addWidget().
Interval duration for dashboard
Interval duration for metrics in dashboard. You can specify defaultInterval with
the relative time(eg. 7 days) as Duration.days(7).
import software.amazon.awscdk.services.cloudwatch.*;
Dashboard dashboard = Dashboard.Builder.create(this, "Dash")
.defaultInterval(Duration.days(7))
.build();
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.
- Property variables can change any JSON property in the JSON source of a dashboard like
region. It can also change the dimension name for a metric. - Pattern variables use a regular expression pattern to change all or part of a JSON property.
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:
import software.amazon.awscdk.services.cloudwatch.*;
Dashboard dashboard = Dashboard.Builder.create(this, "Dash")
.defaultInterval(Duration.days(7))
.variables(List.of(DashboardVariable.Builder.create()
.id("region")
.type(VariableType.PROPERTY)
.label("Region")
.inputType(VariableInputType.RADIO)
.value("region")
.values(Values.fromValues(VariableValue.builder().label("IAD").value("us-east-1").build(), VariableValue.builder().label("DUB").value("us-west-2").build()))
.defaultValue(DefaultValue.value("us-east-1"))
.visible(true)
.build()))
.build();
This example shows how to change region everywhere, assuming the current dashboard is showing region us-east-1 already, by using pattern variable
import software.amazon.awscdk.services.cloudwatch.*;
Dashboard dashboard = Dashboard.Builder.create(this, "Dash")
.defaultInterval(Duration.days(7))
.variables(List.of(DashboardVariable.Builder.create()
.id("region2")
.type(VariableType.PATTERN)
.label("RegionPattern")
.inputType(VariableInputType.INPUT)
.value("us-east-1")
.defaultValue(DefaultValue.value("us-east-1"))
.visible(true)
.build()))
.build();
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 defaultValue with cw.DefaultValue.FIRST indicates that the default value will be the first value returned from the search.
import software.amazon.awscdk.services.cloudwatch.*;
Dashboard dashboard = Dashboard.Builder.create(this, "Dash")
.defaultInterval(Duration.days(7))
.variables(List.of(DashboardVariable.Builder.create()
.id("functionName")
.type(VariableType.PATTERN)
.label("Function")
.inputType(VariableInputType.RADIO)
.value("originalFuncNameInDashboard")
// equivalent to cw.Values.fromSearch('{AWS/Lambda,FunctionName} MetricName=\"Duration\"', 'FunctionName')
.values(Values.fromSearchComponents(SearchComponents.builder()
.namespace("AWS/Lambda")
.dimensions(List.of("FunctionName"))
.metricName("Duration")
.populateFrom("FunctionName")
.build()))
.defaultValue(DefaultValue.FIRST)
.visible(true)
.build()))
.build();
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:
- The monitoring account must be set up as a monitoring account
- The source account must grant permissions to the monitoring account
- 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 accountId property on LogQueryWidget, GraphWidget, AlarmWidget, SingleValueWidget, and GaugeWidget constructs:
Dashboard dashboard;
dashboard.addWidgets(GraphWidget.Builder.create()
// ...
.accountId("123456789012")
.build());
dashboard.addWidgets(LogQueryWidget.Builder.create()
.logGroupNames(List.of("my-log-group"))
// ...
.accountId("123456789012")
.queryLines(List.of("fields @message"))
.build());
-
ClassDescriptionAn alarm on a CloudWatch metric.A fluent builder for
Alarm.Properties for an alarm action.A builder forAlarmActionConfigAn implementation forAlarmActionConfigThe base class for Alarm and CompositeAlarm resources.Properties for Alarms.A builder forAlarmPropsAn implementation forAlarmPropsClass with static functions to build AlarmRule for Composite Alarms.Enumeration indicates state of Alarm used in building Alarm Rule.A dashboard widget that displays alarms in a grid view.A fluent builder forAlarmStatusWidget.Properties for an Alarm Status Widget.A builder forAlarmStatusWidgetPropsAn implementation forAlarmStatusWidgetPropsThe sort possibilities for AlarmStatusWidgets.Display the metric associated with an alarm, including the alarm line.A fluent builder forAlarmWidget.Properties for an AlarmWidget.A builder forAlarmWidgetPropsAn implementation forAlarmWidgetPropsCloudWatch Alarm that uses anomaly detection to trigger alarms.A fluent builder forAnomalyDetectionAlarm.Properties for Anomaly Detection Alarms.A builder forAnomalyDetectionAlarmPropsAn implementation forAnomalyDetectionAlarmPropsProperties needed to make an anomaly detection alarm from a metric.A builder forAnomalyDetectionMetricOptionsAn implementation forAnomalyDetectionMetricOptionsTheAWS::CloudWatch::Alarmtype specifies an alarm and associates it with the specified metric or metric math expression.A fluent builder forCfnAlarm.Dimension is an embedded property of theAWS::CloudWatch::Alarmtype.A builder forCfnAlarm.DimensionPropertyAn implementation forCfnAlarm.DimensionPropertyTheMetricDataQueryproperty type specifies the metric data to return, and whether this call is just retrieving a batch set of data for one metric, or is performing a math expression on metric data.A builder forCfnAlarm.MetricDataQueryPropertyAn implementation forCfnAlarm.MetricDataQueryPropertyTheMetricproperty type represents a specific metric.A builder forCfnAlarm.MetricPropertyAn implementation forCfnAlarm.MetricPropertyThis structure defines the metric to be returned, along with the statistics, period, and units.A builder forCfnAlarm.MetricStatPropertyAn implementation forCfnAlarm.MetricStatPropertyProperties for defining aCfnAlarm.A builder forCfnAlarmPropsAn implementation forCfnAlarmPropsTheAWS::CloudWatch::AnomalyDetectortype specifies an anomaly detection band for a certain metric and statistic.A fluent builder forCfnAnomalyDetector.Specifies details about how the anomaly detection model is to be trained, including time ranges to exclude when training and updating the model.A builder forCfnAnomalyDetector.ConfigurationPropertyAn implementation forCfnAnomalyDetector.ConfigurationPropertyA dimension is a name/value pair that is part of the identity of a metric.A builder forCfnAnomalyDetector.DimensionPropertyAn implementation forCfnAnomalyDetector.DimensionPropertyThis object includes parameters that you can use to provide information to CloudWatch to help it build more accurate anomaly detection models.A builder forCfnAnomalyDetector.MetricCharacteristicsPropertyAn implementation forCfnAnomalyDetector.MetricCharacteristicsPropertyThis structure is used in bothGetMetricDataandPutMetricAlarm.A builder forCfnAnomalyDetector.MetricDataQueryPropertyAn implementation forCfnAnomalyDetector.MetricDataQueryPropertyIndicates the CloudWatch math expression that provides the time series the anomaly detector uses as input.A builder forCfnAnomalyDetector.MetricMathAnomalyDetectorPropertyAn implementation forCfnAnomalyDetector.MetricMathAnomalyDetectorPropertyRepresents a specific metric.A builder forCfnAnomalyDetector.MetricPropertyAn implementation forCfnAnomalyDetector.MetricPropertyThis structure defines the metric to be returned, along with the statistics, period, and units.A builder forCfnAnomalyDetector.MetricStatPropertyAn implementation forCfnAnomalyDetector.MetricStatPropertyEachRangespecifies one range of days or times to exclude from use for training or updating an anomaly detection model.A builder forCfnAnomalyDetector.RangePropertyAn implementation forCfnAnomalyDetector.RangePropertyDesignates the CloudWatch metric and statistic that provides the time series the anomaly detector uses as input.A builder forCfnAnomalyDetector.SingleMetricAnomalyDetectorPropertyAn implementation forCfnAnomalyDetector.SingleMetricAnomalyDetectorPropertyProperties for defining aCfnAnomalyDetector.A builder forCfnAnomalyDetectorPropsAn implementation forCfnAnomalyDetectorPropsTheAWS::CloudWatch::CompositeAlarmtype creates or updates a composite alarm.A fluent builder forCfnCompositeAlarm.Properties for defining aCfnCompositeAlarm.A builder forCfnCompositeAlarmPropsAn implementation forCfnCompositeAlarmPropsTheAWS::CloudWatch::Dashboardresource specifies an Amazon CloudWatch dashboard.A fluent builder forCfnDashboard.Properties for defining aCfnDashboard.A builder forCfnDashboardPropsAn implementation forCfnDashboardPropsCreates or updates a Contributor Insights rule.A fluent builder forCfnInsightRule.Properties for defining aCfnInsightRule.A builder forCfnInsightRulePropsAn implementation forCfnInsightRulePropsCreates or updates a metric stream.A fluent builder forCfnMetricStream.This structure contains a metric namespace and optionally, a list of metric names, to either include in a metric ' stream or exclude from a metric stream.A builder forCfnMetricStream.MetricStreamFilterPropertyAn implementation forCfnMetricStream.MetricStreamFilterPropertyThis structure specifies a list of additional statistics to stream, and the metrics to stream those additional statistics for.An implementation forCfnMetricStream.MetricStreamStatisticsConfigurationPropertyA structure that specifies the metric name and namespace for one metric that is going to have additional statistics included in the stream.A builder forCfnMetricStream.MetricStreamStatisticsMetricPropertyAn implementation forCfnMetricStream.MetricStreamStatisticsMetricPropertyProperties for defining aCfnMetricStream.A builder forCfnMetricStreamPropsAn implementation forCfnMetricStreamPropsA set of standard colours that can be used in annotations in a GraphWidget.A widget that contains other widgets in a vertical column.Options shared by most methods accepting metric options.A builder forCommonMetricOptionsAn implementation forCommonMetricOptionsComparison operator for evaluating alarms.A Composite Alarm based on Alarm Rule.A fluent builder forCompositeAlarm.Properties for creating a Composite Alarm.A builder forCompositeAlarmPropsAn implementation forCompositeAlarmPropsA real CloudWatch widget that has its own fixed size and remembers its position.Properties needed to make an alarm from a metric.A builder forCreateAlarmOptionsAn implementation forCreateAlarmOptionsA CustomWidget shows the result of a AWS lambda function.A fluent builder forCustomWidget.The properties for a CustomWidget.A builder forCustomWidgetPropsAn implementation forCustomWidgetPropsA CloudWatch dashboard.A fluent builder forDashboard.Properties for defining a CloudWatch Dashboard.A builder forDashboardPropsAn implementation forDashboardPropsDashboard Variable.A fluent builder forDashboardVariable.Options forDashboardVariable.A builder forDashboardVariableOptionsAn implementation forDashboardVariableOptionsDefault value for use inDashboardVariableOptions.Metric dimension.A builder forDimensionAn implementation forDimensionA dashboard gauge widget that displays metrics.A fluent builder forGaugeWidget.Properties for a GaugeWidget.A builder forGaugeWidgetPropsAn implementation forGaugeWidgetPropsA dashboard widget that displays metrics.A fluent builder forGraphWidget.Properties for a GraphWidget.A builder forGraphWidgetPropsAn implementation forGraphWidgetPropsTypes of view.Horizontal annotation to be added to a graph.A builder forHorizontalAnnotationAn implementation forHorizontalAnnotationRepresents a CloudWatch Alarm.Internal default implementation forIAlarm.A proxy class which represents a concrete javascript instance of this type.Interface for objects that can be the targets of CloudWatch alarm actions.Internal default implementation forIAlarmAction.A proxy class which represents a concrete javascript instance of this type.Interface for Alarm Rule.Internal default implementation forIAlarmRule.A proxy class which represents a concrete javascript instance of this type.Interface for metrics.Internal default implementation forIMetric.A proxy class which represents a concrete javascript instance of this type.A single dashboard variable.Internal default implementation forIVariable.A proxy class which represents a concrete javascript instance of this type.A single dashboard widget.Internal default implementation forIWidget.A proxy class which represents a concrete javascript instance of this type.The position of the legend on a GraphWidget.Logs Query Language.Types of view.Display query results from Logs Insights.A fluent builder forLogQueryWidget.Properties for a Query widget.A builder forLogQueryWidgetPropsAn implementation forLogQueryWidgetPropsA math expression built with metric(s) emitted by a service.A fluent builder forMathExpression.Configurable options for MathExpressions.A builder forMathExpressionOptionsAn implementation forMathExpressionOptionsProperties for a MathExpression.A builder forMathExpressionPropsAn implementation forMathExpressionPropsA metric emitted by a service.A fluent builder forMetric.Properties of a rendered metric.A builder forMetricConfigAn implementation forMetricConfigProperties for a concrete metric.A builder forMetricExpressionConfigAn implementation forMetricExpressionConfigProperties of a metric that can be changed.A builder forMetricOptionsAn implementation forMetricOptionsProperties for a metric.A builder forMetricPropsAn implementation forMetricPropsProperties for a concrete metric.A builder forMetricStatConfigAn implementation forMetricStatConfigBasic properties for widgets that display metrics.A builder forMetricWidgetPropsAn implementation forMetricWidgetPropsSpecify the period for graphs when the CloudWatch dashboard loads.A widget that contains other widgets in a horizontal row.Search components for use with.invalid reference
Values.fromSearchComponentsA builder forSearchComponentsAn implementation forSearchComponentsA CloudWatch search expression for dynamically finding and graphing multiple related metrics.A fluent builder forSearchExpression.Configurable options for SearchExpressions.A builder forSearchExpressionOptionsAn implementation forSearchExpressionOptionsProperties for a SearchExpression.A builder forSearchExpressionPropsAn implementation forSearchExpressionPropsFill shading options that will be used with a horizontal annotation.A dashboard widget that displays the most recent value for every metric.A fluent builder forSingleValueWidget.Properties for a SingleValueWidget.A builder forSingleValueWidgetPropsAn implementation forSingleValueWidgetPropsA widget that doesn't display anything but takes up space.A fluent builder forSpacer.Props of the spacer.A builder forSpacerPropsAn implementation forSpacerPropsDeprecated.Factory functions for standard statistics strings.Layout for TableWidget.Standard table summary columns.Properties for TableWidget's summary columns.A builder forTableSummaryPropsAn implementation forTableSummaryPropsThresholds for highlighting cells in TableWidget.A dashboard widget that displays metrics.A fluent builder forTableWidget.Properties for a TableWidget.A builder forTableWidgetPropsAn implementation forTableWidgetPropsA dashboard widget that displays MarkDown.A fluent builder forTextWidget.Background types available.Properties for a Text widget.A builder forTextWidgetPropsAn implementation forTextWidgetPropsSpecify how missing data points are treated during alarm evaluation.Unit for metric.A class for providing values for use withandinvalid reference
VariableInputType.SELECTdashboard variables.invalid reference
VariableInputType.RADIOExample:Example:Example:A builder forVariableValueAn implementation forVariableValueVertical annotation to be added to a graph.A builder forVerticalAnnotationAn implementation forVerticalAnnotationFill shading options that will be used with a vertical annotation.Properties for a Y-Axis.A builder forYAxisPropsAn implementation forYAxisProps
Statsto produce statistics strings