Package: aws-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 theMigrating to AWS CDK v2guide.Metric objectsMetric objects represent a metric that is emitted by AWS services or your own
application, such asCPUUsage,FailureCountorBandwidth.Metric objects can be constructed directly or are exposed by resources as
attributes. Resources that expose metrics will have functions that look
likemetricXxx()which will return a Metric object, initialized with defaults
that make sense.For example,lambda.Functionobjects have thefn.metricErrors()method, which
represents the amount of errors reported by that Lambda function:# fn: lambda.Functionerrors=fn.metric_errors()Metricobjects can be account and region aware. You can specifyaccountandregionas properties of the metric, or use themetric.attachTo(Construct)method.metric.attachTo()will automatically copy theregionandaccountfields of theConstruct, which can come from anywhere in the Construct tree.You can also instantiateMetricobjects to reference anypublished metricthat's not exposed using a convenience method on the CDK construct.
For example:hosted_zone=route53.HostedZone(self,"MyHostedZone",zone_name="example.org")metric=cloudwatch.Metric(namespace="AWS/Route53",metric_name="DNSQueries",dimensions_map={"HostedZoneId":hosted_zone.hosted_zone_id})Instantiating a new Metric objectIf you want to reference a metric that is not yet exposed by an existing construct,
you can instantiate aMetricobject to represent it. For example:metric=cloudwatch.Metric(namespace="MyNamespace",metric_name="MyMetric",dimensions_map={"ProcessingStep":"Download"})Metric MathMath expressions are supported by instantiating theMathExpressionclass.
For example, a math expression that sums two other metrics looks like this:# fn: lambda.Functionall_problems=cloudwatch.MathExpression(expression="errors + throttles",using_metrics={"errors":fn.metric_errors(),"faults":fn.metric_throttles()})You can useMathExpressionobjects like any other metric, including using
them in other math expressions:# fn: lambda.Function# all_problems: cloudwatch.MathExpressionproblem_percentage=cloudwatch.MathExpression(expression="(problems / invocations) * 100",using_metrics={"problems":all_problems,"invocations":fn.metric_invocations()})Search ExpressionsMath 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:cpu_utilization=cloudwatch.MathExpression(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
thesearchAccountandsearchRegionproperties to specify the account
and/or region to evaluate the search expression against.AggregationTo graph or alarm on metrics you must aggregate them first, using a function
likeAverageor a percentile function likeP99. By default, most Metric objects
returned by CDK libraries will be configured asAverageover300 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 asSumover300 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: lambda.Functionminute_error_rate=fn.metric_errors(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 SumsThe reason for usingSumto count discrete events is thatsomeevents are
emitted as either0or1(for exampleErrorsfor a Lambda) and some are
only emitted as1(for exampleNumberOfMessagesPublishedfor an SNS
topic).In case0-metrics are emitted, it makes sense to take theAverageof this
metric: the result will be the fraction of errors over all executions.If0-metrics are not emitted, theAveragewill always be equal to1,
and not be very useful.In order to simplify the mental model ofMetricobjects, 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.LabelsMetric labels are displayed in the legend of graphs that include the metrics.You can usedynamic labelsto show summary information about the displayed time series
in the legend. For example, if you use:# fn: lambda.Functionminute_error_rate=fn.metric_errors(statistic="sum",period=Duration.hours(1),# Show the maximum hourly error count in the legendlabel="[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.AlarmsAlarms can be created on metrics in one of two ways. Either create anAlarmobject, passing theMetricobject to set the alarm on:# fn: lambda.Functioncloudwatch.Alarm(self,"Alarm",metric=fn.metric_errors(),threshold=100,evaluation_periods=2)Alternatively, you can callmetric.createAlarm():# fn: lambda.Functionfn.metric_errors().create_alarm(self,"Alarm",threshold=100,evaluation_periods=2)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 the threshold for the alarm to trigger.To create a cross-account alarm, make sure you have enabledcross-account functionalityin CloudWatch. Then, set theaccountproperty in theMetricobject either manually or via themetric.attachTo()method.Alarm ActionsTo add actions to an alarm, use the integration classes from the@aws-cdk/aws-cloudwatch-actionspackage. For example, to post a message to
an SNS topic when an alarm breaches, do the following:importaws_cdk.aws_cloudwatch_actionsascw_actions# alarm: cloudwatch.Alarmtopic=sns.Topic(self,"Topic")alarm.add_alarm_action(cw_actions.SnsAction(topic))Notification formatsAlarms 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 mathCross-account metricsLabelsThe difference between these two does not impact the functionality of the alarm
in any way,exceptthat 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 AlarmsComposite Alarmscan be created from existing Alarm resources.# alarm1: cloudwatch.Alarm# alarm2: cloudwatch.Alarm# alarm3: cloudwatch.Alarm# alarm4: cloudwatch.Alarmalarm_rule=cloudwatch.AlarmRule.any_of(cloudwatch.AlarmRule.all_of(cloudwatch.AlarmRule.any_of(alarm1,cloudwatch.AlarmRule.from_alarm(alarm2,cloudwatch.AlarmState.OK),alarm3),cloudwatch.AlarmRule.not(cloudwatch.AlarmRule.from_alarm(alarm4,cloudwatch.AlarmState.INSUFFICIENT_DATA))),cloudwatch.AlarmRule.from_boolean(False))cloudwatch.CompositeAlarm(self,"MyAwesomeCompositeAlarm",alarm_rule=alarm_rule)A note on unitsIn CloudWatch, Metrics datums are emitted with units, such assecondsorbytes. WhenMetricobjects are given aunitattribute, it will be used tofilterthe stream of metric datums for datums emitted using the sameunitattribute.In particular, theunitfield isnotused to rescale datums or alarm threshold
values (for example, it cannot be used to specify an alarm threshold inMegabytesif the metric stream is being emitted asbytes).You almost certainly don't want to specify theunitproperty when creatingMetricobjects (which will retrieve all datums regardless of their unit),
unless you have very specific requirements. Note that in any case, CloudWatch
only supports filtering byunitfor 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/5595DashboardsDashboards 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 widgetA graph widget can display any number of metrics on either theleftorrightvertical axis:# dashboard: cloudwatch.Dashboard# execution_count_metric: cloudwatch.Metric# error_count_metric: cloudwatch.Metricdashboard.add_widgets(cloudwatch.GraphWidget(title="Executions vs error rate",left=[execution_count_metric],right=[error_count_metric.with(statistic="average",label="Error rate",color=cloudwatch.Color.GREEN)]))Using the methodsaddLeftMetric()andaddRightMetric()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: cloudwatch.Dashboarddashboard.add_widgets(cloudwatch.GraphWidget(# ...left_annotations=[cloudwatch.HorizontalAnnotation(value=1800,label=Duration.minutes(30).to_human_string(),color=cloudwatch.Color.RED),cloudwatch.HorizontalAnnotation(value=3600,label="1 hour",color="#2ca02c")]))The graph legend can be adjusted from the default position at bottom of the widget.# dashboard: cloudwatch.Dashboarddashboard.add_widgets(cloudwatch.GraphWidget(# ...legend_position=cloudwatch.LegendPosition.RIGHT))The graph can publish live data within the last minute that has not been fully aggregated.# dashboard: cloudwatch.Dashboarddashboard.add_widgets(cloudwatch.GraphWidget(# ...live_data=True))The graph view can be changed from default 'timeSeries' to 'bar' or 'pie'.# dashboard: cloudwatch.Dashboarddashboard.add_widgets(cloudwatch.GraphWidget(# ...view=cloudwatch.GraphWidgetView.BAR))Alarm widgetAn alarm widget shows the graph and the alarm line of a single alarm:# dashboard: cloudwatch.Dashboard# error_alarm: cloudwatch.Alarmdashboard.add_widgets(cloudwatch.AlarmWidget(title="Errors",alarm=error_alarm))Single value widgetA single-value widget shows the latest value of a set of metrics (as opposed
to a graph of the value over time):# dashboard: cloudwatch.Dashboard# visitor_count: cloudwatch.Metric# purchase_count: cloudwatch.Metricdashboard.add_widgets(cloudwatch.SingleValueWidget(metrics=[visitor_count,purchase_count]))Show as many digits as can fit, before rounding.# dashboard: cloudwatch.Dashboarddashboard.add_widgets(cloudwatch.SingleValueWidget(metrics=[],full_precision=True))Text widgetA text widget shows an arbitrary piece of MarkDown. Use this to add explanations
to your dashboard:# dashboard: cloudwatch.Dashboarddashboard.add_widgets(cloudwatch.TextWidget(markdown="# Key Performance Indicators"))Alarm Status widgetAn 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: cloudwatch.Dashboard# error_alarm: cloudwatch.Alarmdashboard.add_widgets(cloudwatch.AlarmStatusWidget(alarms=[error_alarm]))An alarm status widget only showing firing alarms, sorted by state and timestamp:# dashboard: cloudwatch.Dashboard# error_alarm: cloudwatch.Alarmdashboard.add_widgets(cloudwatch.AlarmStatusWidget(title="Errors",alarms=[error_alarm],sort_by=cloudwatch.AlarmStatusWidgetSortBy.STATE_UPDATED_TIMESTAMP,states=[cloudwatch.AlarmState.ALARM]))Query results widgetALogQueryWidgetshows the results of a query from Logs Insights:# dashboard: cloudwatch.Dashboarddashboard.add_widgets(cloudwatch.LogQueryWidget(log_group_names=["my-log-group"],view=cloudwatch.LogQueryVisualizationType.TABLE,# The lines will be automatically combined using '\n|'.query_lines=["fields @message","filter @message like /Error/"]))Custom widgetACustomWidgetshows the result of an AWS Lambda function:# dashboard: cloudwatch.Dashboard# Import or create a lambda functionfn=lambda_.Function.from_function_arn(dashboard,"Function","arn:aws:lambda:us-east-1:123456789012:function:MyFn")dashboard.add_widgets(cloudwatch.CustomWidget(function_arn=fn.function_arn,title="My lambda baked widget"))You can learn more about custom widgets in theAmazon Cloudwatch User Guide.Dashboard LayoutThe 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 awidthandheightproperty, 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 callingadd(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