Namespace Amazon.CDK.AWS.CloudWatch
Amazon CloudWatch Construct Library
---AWS CDK v1 has reached End-of-Support on 2023-06-01.
This package is no longer being updated, and users should migrate to AWS CDK v2.
For more information on how to migrate, see the Migrating to AWS CDK v2 guide.
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;
var 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:
var hostedZone = new HostedZone(this, "MyHostedZone", new HostedZoneProps { ZoneName = "example.org" });
var metric = new Metric(new MetricProps {
Namespace = "AWS/Route53",
MetricName = "DNSQueries",
DimensionsMap = new Dictionary<string, string> {
{ "HostedZoneId", hostedZone.HostedZoneId }
}
});
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:
var metric = new Metric(new MetricProps {
Namespace = "MyNamespace",
MetricName = "MyMetric",
DimensionsMap = new Dictionary<string, string> {
{ "ProcessingStep", "Download" }
}
});
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;
var allProblems = new MathExpression(new MathExpressionProps {
Expression = "errors + throttles",
UsingMetrics = new Dictionary<string, IMetric> {
{ "errors", fn.MetricErrors() },
{ "faults", fn.MetricThrottles() }
}
});
You can use MathExpression
objects like any other metric, including using
them in other math expressions:
Function fn;
MathExpression allProblems;
var problemPercentage = new MathExpression(new MathExpressionProps {
Expression = "(problems / invocations) * 100",
UsingMetrics = new Dictionary<string, IMetric> {
{ "problems", allProblems },
{ "invocations", fn.MetricInvocations() }
}
});
Search Expressions
Math expressions also support search expressions. For example, the following search expression returns all CPUUtilization metrics that it finds, with the graph showing the Average statistic with an aggregation period of 5 minutes:
var cpuUtilization = new MathExpression(new MathExpressionProps {
Expression = "SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 300)",
// Specifying '' as the label suppresses the default behavior
// of using the expression as metric label. This is especially appropriate
// when using expressions that return multiple time series (like SEARCH()
// or METRICS()), to show the labels of the retrieved metrics only.
Label = ""
});
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.
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;
var minuteErrorRate = fn.MetricErrors(new MetricOptions {
Statistic = "avg",
Period = Duration.Minutes(1),
Label = "Lambda failure rate"
});
This 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.
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;
var minuteErrorRate = fn.MetricErrors(new MetricOptions {
Statistic = "sum",
Period = 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:
Function fn;
new Alarm(this, "Alarm", new AlarmProps {
Metric = fn.MetricErrors(),
Threshold = 100,
EvaluationPeriods = 2
});
Alternatively, you can call metric.createAlarm()
:
Function fn;
fn.MetricErrors().CreateAlarm(this, "Alarm", new CreateAlarmOptions {
Threshold = 100,
EvaluationPeriods = 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.
Alarm Actions
To add actions to an alarm, use the integration classes from the
@aws-cdk/aws-cloudwatch-actions
package. For example, to post a message to
an SNS topic when an alarm breaches, do the following:
using Amazon.CDK.AWS.CloudWatch.Actions;
Alarm alarm;
var topic = new Topic(this, "Topic");
alarm.AddAlarmAction(new SnsAction(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.
Alarm alarm1;
Alarm alarm2;
Alarm alarm3;
Alarm alarm4;
var 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));
new CompositeAlarm(this, "MyAwesomeCompositeAlarm", new CompositeAlarmProps {
AlarmRule = alarmRule
});
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
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 dashboard;
Metric executionCountMetric;
Metric errorCountMetric;
dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
Title = "Executions vs error rate",
Left = new [] { executionCountMetric },
Right = new [] { errorCountMetric.With(new MetricOptions {
Statistic = "average",
Label = "Error rate",
Color = Color.GREEN
}) }
}));
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 the right y-axis.
Dashboard dashboard;
dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
// ...
LeftAnnotations = new [] { new HorizontalAnnotation { Value = 1800, Label = Duration.Minutes(30).ToHumanString(), Color = Color.RED }, new HorizontalAnnotation { Value = 3600, Label = "1 hour", Color = "#2ca02c" } }
}));
The graph legend can be adjusted from the default position at bottom of the widget.
Dashboard dashboard;
dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
// ...
LegendPosition = LegendPosition.RIGHT
}));
The graph can publish live data within the last minute that has not been fully aggregated.
Dashboard dashboard;
dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
// ...
LiveData = true
}));
The graph view can be changed from default 'timeSeries' to 'bar' or 'pie'.
Dashboard dashboard;
dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
// ...
View = GraphWidgetView.BAR
}));
Alarm widget
An alarm widget shows the graph and the alarm line of a single alarm:
Dashboard dashboard;
Alarm errorAlarm;
dashboard.AddWidgets(new AlarmWidget(new AlarmWidgetProps {
Title = "Errors",
Alarm = errorAlarm
}));
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(new SingleValueWidget(new SingleValueWidgetProps {
Metrics = new [] { visitorCount, purchaseCount }
}));
Show as many digits as can fit, before rounding.
Dashboard dashboard;
dashboard.AddWidgets(new SingleValueWidget(new SingleValueWidgetProps {
Metrics = new [] { },
FullPrecision = true
}));
Text widget
A text widget shows an arbitrary piece of MarkDown. Use this to add explanations to your dashboard:
Dashboard dashboard;
dashboard.AddWidgets(new TextWidget(new TextWidgetProps {
Markdown = "# Key Performance Indicators"
}));
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(
new AlarmStatusWidget(new AlarmStatusWidgetProps {
Alarms = new [] { errorAlarm }
}));
An alarm status widget only showing firing alarms, sorted by state and timestamp:
Dashboard dashboard;
Alarm errorAlarm;
dashboard.AddWidgets(new AlarmStatusWidget(new AlarmStatusWidgetProps {
Title = "Errors",
Alarms = new [] { errorAlarm },
SortBy = AlarmStatusWidgetSortBy.STATE_UPDATED_TIMESTAMP,
States = new [] { AlarmState.ALARM }
}));
Query results widget
A LogQueryWidget
shows the results of a query from Logs Insights:
Dashboard dashboard;
dashboard.AddWidgets(new LogQueryWidget(new LogQueryWidgetProps {
LogGroupNames = new [] { "my-log-group" },
View = LogQueryVisualizationType.TABLE,
// The lines will be automatically combined using '\n|'.
QueryLines = new [] { "fields @message", "filter @message like /Error/" }
}));
Custom widget
A CustomWidget
shows the result of an AWS Lambda function:
Dashboard dashboard;
// Import or create a lambda function
var fn = Function.FromFunctionArn(dashboard, "Function", "arn:aws:lambda:us-east-1:123456789012:function:MyFn");
dashboard.AddWidgets(new CustomWidget(new CustomWidgetProps {
FunctionArn = fn.FunctionArn,
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:
Classes
Alarm | An alarm on a CloudWatch metric. |
AlarmActionConfig | Properties for an alarm action. |
AlarmBase | The base class for Alarm and CompositeAlarm resources. |
AlarmProps | Properties for Alarms. |
AlarmRule | Class with static functions to build AlarmRule for Composite Alarms. |
AlarmState | Enumeration indicates state of Alarm used in building Alarm Rule. |
AlarmStatusWidget | A dashboard widget that displays alarms in a grid view. |
AlarmStatusWidgetProps | Properties for an Alarm Status Widget. |
AlarmStatusWidgetSortBy | The sort possibilities for AlarmStatusWidgets. |
AlarmWidget | Display the metric associated with an alarm, including the alarm line. |
AlarmWidgetProps | Properties for an AlarmWidget. |
CfnAlarm | A CloudFormation |
CfnAlarm.DimensionProperty | Dimension is an embedded property of the |
CfnAlarm.MetricDataQueryProperty | The |
CfnAlarm.MetricProperty | The |
CfnAlarm.MetricStatProperty | This structure defines the metric to be returned, along with the statistics, period, and units. |
CfnAlarmProps | Properties for defining a |
CfnAnomalyDetector | A CloudFormation |
CfnAnomalyDetector.ConfigurationProperty | Specifies details about how the anomaly detection model is to be trained, including time ranges to exclude when training and updating the model. |
CfnAnomalyDetector.DimensionProperty | A dimension is a name/value pair that is part of the identity of a metric. |
CfnAnomalyDetector.MetricDataQueryProperty | This structure is used in both |
CfnAnomalyDetector.MetricMathAnomalyDetectorProperty | Indicates the CloudWatch math expression that provides the time series the anomaly detector uses as input. |
CfnAnomalyDetector.MetricProperty | Represents a specific metric. |
CfnAnomalyDetector.MetricStatProperty | This structure defines the metric to be returned, along with the statistics, period, and units. |
CfnAnomalyDetector.RangeProperty | Each |
CfnAnomalyDetector.SingleMetricAnomalyDetectorProperty | Designates the CloudWatch metric and statistic that provides the time series the anomaly detector uses as input. |
CfnAnomalyDetectorProps | Properties for defining a |
CfnCompositeAlarm | A CloudFormation |
CfnCompositeAlarmProps | Properties for defining a |
CfnDashboard | A CloudFormation |
CfnDashboardProps | Properties for defining a |
CfnInsightRule | A CloudFormation |
CfnInsightRuleProps | Properties for defining a |
CfnMetricStream | A CloudFormation |
CfnMetricStream.MetricStreamFilterProperty | 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. |
CfnMetricStream.MetricStreamStatisticsConfigurationProperty | This structure specifies a list of additional statistics to stream, and the metrics to stream those additional statistics for. |
CfnMetricStream.MetricStreamStatisticsMetricProperty | A structure that specifies the metric name and namespace for one metric that is going to have additional statistics included in the stream. |
CfnMetricStreamProps | Properties for defining a |
Color | A set of standard colours that can be used in annotations in a GraphWidget. |
Column | A widget that contains other widgets in a vertical column. |
CommonMetricOptions | Options shared by most methods accepting metric options. |
ComparisonOperator | Comparison operator for evaluating alarms. |
CompositeAlarm | A Composite Alarm based on Alarm Rule. |
CompositeAlarmProps | Properties for creating a Composite Alarm. |
ConcreteWidget | A real CloudWatch widget that has its own fixed size and remembers its position. |
CreateAlarmOptions | Properties needed to make an alarm from a metric. |
CustomWidget | A CustomWidget shows the result of a AWS lambda function. |
CustomWidgetProps | The properties for a CustomWidget. |
Dashboard | A CloudWatch dashboard. |
DashboardProps | Properties for defining a CloudWatch Dashboard. |
Dimension | Metric dimension. |
GraphWidget | A dashboard widget that displays metrics. |
GraphWidgetProps | Properties for a GraphWidget. |
GraphWidgetView | Types of view. |
HorizontalAnnotation | Horizontal annotation to be added to a graph. |
LegendPosition | The position of the legend on a GraphWidget. |
LogQueryVisualizationType | Types of view. |
LogQueryWidget | Display query results from Logs Insights. |
LogQueryWidgetProps | Properties for a Query widget. |
MathExpression | A math expression built with metric(s) emitted by a service. |
MathExpressionOptions | Configurable options for MathExpressions. |
MathExpressionProps | Properties for a MathExpression. |
Metric | A metric emitted by a service. |
MetricAlarmConfig | (deprecated) Properties used to construct the Metric identifying part of an Alarm. |
MetricConfig | Properties of a rendered metric. |
MetricExpressionConfig | Properties for a concrete metric. |
MetricGraphConfig | (deprecated) Properties used to construct the Metric identifying part of a Graph. |
MetricOptions | Properties of a metric that can be changed. |
MetricProps | Properties for a metric. |
MetricRenderingProperties | (deprecated) Custom rendering properties that override the default rendering properties specified in the yAxis parameter of the widget object. |
MetricStatConfig | Properties for a concrete metric. |
MetricWidgetProps | Basic properties for widgets that display metrics. |
PeriodOverride | Specify the period for graphs when the CloudWatch dashboard loads. |
Row | A widget that contains other widgets in a horizontal row. |
Shading | Fill shading options that will be used with an annotation. |
SingleValueWidget | A dashboard widget that displays the most recent value for every metric. |
SingleValueWidgetProps | Properties for a SingleValueWidget. |
Spacer | A widget that doesn't display anything but takes up space. |
SpacerProps | Props of the spacer. |
Statistic | Statistic to use over the aggregation period. |
TextWidget | A dashboard widget that displays MarkDown. |
TextWidgetProps | Properties for a Text widget. |
TreatMissingData | Specify how missing data points are treated during alarm evaluation. |
Unit | Unit for metric. |
YAxisProps | Properties for a Y-Axis. |
Interfaces
CfnAlarm.IDimensionProperty | Dimension is an embedded property of the |
CfnAlarm.IMetricDataQueryProperty | The |
CfnAlarm.IMetricProperty | The |
CfnAlarm.IMetricStatProperty | This structure defines the metric to be returned, along with the statistics, period, and units. |
CfnAnomalyDetector.IConfigurationProperty | Specifies details about how the anomaly detection model is to be trained, including time ranges to exclude when training and updating the model. |
CfnAnomalyDetector.IDimensionProperty | A dimension is a name/value pair that is part of the identity of a metric. |
CfnAnomalyDetector.IMetricDataQueryProperty | This structure is used in both |
CfnAnomalyDetector.IMetricMathAnomalyDetectorProperty | Indicates the CloudWatch math expression that provides the time series the anomaly detector uses as input. |
CfnAnomalyDetector.IMetricProperty | Represents a specific metric. |
CfnAnomalyDetector.IMetricStatProperty | This structure defines the metric to be returned, along with the statistics, period, and units. |
CfnAnomalyDetector.IRangeProperty | Each |
CfnAnomalyDetector.ISingleMetricAnomalyDetectorProperty | Designates the CloudWatch metric and statistic that provides the time series the anomaly detector uses as input. |
CfnMetricStream.IMetricStreamFilterProperty | 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. |
CfnMetricStream.IMetricStreamStatisticsConfigurationProperty | This structure specifies a list of additional statistics to stream, and the metrics to stream those additional statistics for. |
CfnMetricStream.IMetricStreamStatisticsMetricProperty | A structure that specifies the metric name and namespace for one metric that is going to have additional statistics included in the stream. |
IAlarm | Represents a CloudWatch Alarm. |
IAlarmAction | Interface for objects that can be the targets of CloudWatch alarm actions. |
IAlarmActionConfig | Properties for an alarm action. |
IAlarmProps | Properties for Alarms. |
IAlarmRule | Interface for Alarm Rule. |
IAlarmStatusWidgetProps | Properties for an Alarm Status Widget. |
IAlarmWidgetProps | Properties for an AlarmWidget. |
ICfnAlarmProps | Properties for defining a |
ICfnAnomalyDetectorProps | Properties for defining a |
ICfnCompositeAlarmProps | Properties for defining a |
ICfnDashboardProps | Properties for defining a |
ICfnInsightRuleProps | Properties for defining a |
ICfnMetricStreamProps | Properties for defining a |
ICommonMetricOptions | Options shared by most methods accepting metric options. |
ICompositeAlarmProps | Properties for creating a Composite Alarm. |
ICreateAlarmOptions | Properties needed to make an alarm from a metric. |
ICustomWidgetProps | The properties for a CustomWidget. |
IDashboardProps | Properties for defining a CloudWatch Dashboard. |
IDimension | Metric dimension. |
IGraphWidgetProps | Properties for a GraphWidget. |
IHorizontalAnnotation | Horizontal annotation to be added to a graph. |
ILogQueryWidgetProps | Properties for a Query widget. |
IMathExpressionOptions | Configurable options for MathExpressions. |
IMathExpressionProps | Properties for a MathExpression. |
IMetric | Interface for metrics. |
IMetricAlarmConfig | (deprecated) Properties used to construct the Metric identifying part of an Alarm. |
IMetricConfig | Properties of a rendered metric. |
IMetricExpressionConfig | Properties for a concrete metric. |
IMetricGraphConfig | (deprecated) Properties used to construct the Metric identifying part of a Graph. |
IMetricOptions | Properties of a metric that can be changed. |
IMetricProps | Properties for a metric. |
IMetricRenderingProperties | (deprecated) Custom rendering properties that override the default rendering properties specified in the yAxis parameter of the widget object. |
IMetricStatConfig | Properties for a concrete metric. |
IMetricWidgetProps | Basic properties for widgets that display metrics. |
ISingleValueWidgetProps | Properties for a SingleValueWidget. |
ISpacerProps | Props of the spacer. |
ITextWidgetProps | Properties for a Text widget. |
IWidget | A single dashboard widget. |
IYAxisProps | Properties for a Y-Axis. |