package
2.166.0
Repository: https://github.com/aws/aws-cdk-go.git
Documentation: pkg.go.dev

# README

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:

var fn function


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 := route53.NewHostedZone(this, jsii.String("MyHostedZone"), &HostedZoneProps{
	ZoneName: jsii.String("example.org"),
})
metric := cloudwatch.NewMetric(&MetricProps{
	Namespace: jsii.String("AWS/Route53"),
	MetricName: jsii.String("DNSQueries"),
	DimensionsMap: map[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:

metric := cloudwatch.NewMetric(&MetricProps{
	Namespace: jsii.String("MyNamespace"),
	MetricName: jsii.String("MyMetric"),
	DimensionsMap: map[string]*string{
		"ProcessingStep": jsii.String("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:

var fn function


allProblems := cloudwatch.NewMathExpression(&MathExpressionProps{
	Expression: jsii.String("errors + throttles"),
	UsingMetrics: map[string]iMetric{
		"errors": fn.metricErrors(),
		"throttles": fn.metricThrottles(),
	},
})

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

var fn function
var allProblems mathExpression


problemPercentage := cloudwatch.NewMathExpression(&MathExpressionProps{
	Expression: jsii.String("(problems / invocations) * 100"),
	UsingMetrics: map[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:

cpuUtilization := cloudwatch.NewMathExpression(&MathExpressionProps{
	Expression: jsii.String("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: jsii.String(""),
})

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:

var fn function


minuteErrorRate := fn.metricErrors(&MetricOptions{
	Statistic: cloudwatch.Stats_AVERAGE(),
	Period: awscdk.Duration_Minutes(jsii.Number(1)),
	Label: jsii.String("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 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 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:

StatisticShort formatLong formatFactory name
SampleCount (n)Stats.SAMPLE_COUNT
Average (avg)Stats.AVERAGE
SumStats.SUM
Minimum (min)Stats.MINIMUM
Maximum (max)Stats.MAXIMUM
Interquartile mean (IQM)Stats.IQM
Percentile (p)p99Stats.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.

var hostedZone hostedZone


cloudwatch.NewMetric(&MetricProps{
	Namespace: jsii.String("AWS/Route53"),
	MetricName: jsii.String("DNSQueries"),
	DimensionsMap: map[string]*string{
		"HostedZoneId": hostedZone.hostedZoneId,
	},
	Statistic: cloudwatch.Stats_SAMPLE_COUNT(),
	Period: awscdk.Duration_Minutes(jsii.Number(5)),
})

cloudwatch.NewMetric(&MetricProps{
	Namespace: jsii.String("AWS/Route53"),
	MetricName: jsii.String("DNSQueries"),
	DimensionsMap: map[string]*string{
		"HostedZoneId": hostedZone.hostedZoneId,
	},
	Statistic: cloudwatch.Stats_P(jsii.Number(99)),
	Period: awscdk.Duration_*Minutes(jsii.Number(5)),
})

cloudwatch.NewMetric(&MetricProps{
	Namespace: jsii.String("AWS/Route53"),
	MetricName: jsii.String("DNSQueries"),
	DimensionsMap: map[string]*string{
		"HostedZoneId": hostedZone.hostedZoneId,
	},
	Statistic: jsii.String("TS(7.5%:90%)"),
	Period: awscdk.Duration_*Minutes(jsii.Number(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:

var fn function


minuteErrorRate := fn.metricErrors(&MetricOptions{
	Statistic: cloudwatch.Stats_SUM(),
	Period: awscdk.Duration_Hours(jsii.Number(1)),

	// Show the maximum hourly error count in the legend
	Label: jsii.String("[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:

var fn function


cloudwatch.NewAlarm(this, jsii.String("Alarm"), &AlarmProps{
	Metric: fn.metricErrors(),
	Threshold: jsii.Number(100),
	EvaluationPeriods: jsii.Number(2),
})

Alternatively, you can call metric.createAlarm():

var fn function


fn.metricErrors().CreateAlarm(this, jsii.String("Alarm"), &CreateAlarmOptions{
	Threshold: jsii.Number(100),
	EvaluationPeriods: jsii.Number(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 to metric >= 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:

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 cw_actions "github.com/aws/aws-cdk-go/awscdk"
var alarm alarm


topic := sns.NewTopic(this, jsii.String("Topic"))
alarm.AddAlarmAction(cw_actions.NewSnsAction(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.

var alarm1 alarm
var alarm2 alarm
var alarm3 alarm
var alarm4 alarm


alarmRule := cloudwatch.AlarmRule_AnyOf(cloudwatch.AlarmRule_AllOf(cloudwatch.AlarmRule_AnyOf(alarm1, cloudwatch.AlarmRule_FromAlarm(alarm2, cloudwatch.AlarmState_OK), alarm3), cloudwatch.AlarmRule_Not(cloudwatch.AlarmRule_FromAlarm(alarm4, cloudwatch.AlarmState_INSUFFICIENT_DATA))), cloudwatch.AlarmRule_FromBoolean(jsii.Boolean(false)))

cloudwatch.NewCompositeAlarm(this, jsii.String("MyAwesomeCompositeAlarm"), &CompositeAlarmProps{
	AlarmRule: AlarmRule,
})

Actions Suppressor

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

var alarm1 alarm
var alarm2 alarm
var onAlarmAction iAlarmAction
var onOkAction iAlarmAction
var actionsSuppressor alarm


alarmRule := cloudwatch.AlarmRule_AnyOf(alarm1, alarm2)

myCompositeAlarm := cloudwatch.NewCompositeAlarm(this, jsii.String("MyAwesomeCompositeAlarm"), &CompositeAlarmProps{
	AlarmRule: AlarmRule,
	ActionsSuppressor: ActionsSuppressor,
})
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

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:

var dashboard dashboard
var executionCountMetric metric
var errorCountMetric metric


dashboard.AddWidgets(cloudwatch.NewGraphWidget(&GraphWidgetProps{
	Title: jsii.String("Executions vs error rate"),

	Left: []iMetric{
		executionCountMetric,
	},

	Right: []*iMetric{
		errorCountMetric.With(&MetricOptions{
			Statistic: cloudwatch.Stats_AVERAGE(),
			Label: jsii.String("Error rate"),
			Color: cloudwatch.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 right y-axis or the x-axis.

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewGraphWidget(&GraphWidgetProps{
	// ...

	LeftAnnotations: []horizontalAnnotation{
		&horizontalAnnotation{
			Value: jsii.Number(1800),
			Label: awscdk.Duration_Minutes(jsii.Number(30)).ToHumanString(),
			Color: cloudwatch.Color_RED(),
		},
		&horizontalAnnotation{
			Value: jsii.Number(3600),
			Label: jsii.String("1 hour"),
			Color: jsii.String("#2ca02c"),
		},
	},
	VerticalAnnotations: []verticalAnnotation{
		&verticalAnnotation{
			Date: jsii.String("2022-10-19T00:00:00Z"),
			Label: jsii.String("Deployment"),
			Color: cloudwatch.Color_RED(),
		},
	},
}))

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

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewGraphWidget(&GraphWidgetProps{
	// ...

	LegendPosition: cloudwatch.LegendPosition_RIGHT,
}))

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

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewGraphWidget(&GraphWidgetProps{
	// ...

	LiveData: jsii.Boolean(true),
}))

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

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewGraphWidget(&GraphWidgetProps{
	// ...

	View: cloudwatch.GraphWidgetView_BAR,
}))

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.

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewGraphWidget(&GraphWidgetProps{
	// ...

	Start: jsii.String("-P7D"),
	End: jsii.String("2018-12-17T06:00:00.000Z"),
}))

Table Widget

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

var dashboard dashboard
var executionCountMetric metric


dashboard.AddWidgets(cloudwatch.NewTableWidget(&TableWidgetProps{
	Title: jsii.String("Executions"),
	Metrics: []iMetric{
		executionCountMetric,
	},
}))

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.

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewTableWidget(&TableWidgetProps{
	// ...

	Layout: 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 (hideNonSummaryColumns sub property).

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewTableWidget(&TableWidgetProps{
	// ...

	Summary: &TableSummaryProps{
		Columns: []tableSummaryColumn{
			cloudwatch.*tableSummaryColumn_AVERAGE,
		},
		HideNonSummaryColumns: jsii.Boolean(true),
		Sticky: jsii.Boolean(true),
	},
}))

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

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewTableWidget(&TableWidgetProps{
	// ...

	Thresholds: []tableThreshold{
		cloudwatch.*tableThreshold_Above(jsii.Number(1000), cloudwatch.Color_RED()),
		cloudwatch.*tableThreshold_Between(jsii.Number(500), jsii.Number(1000), cloudwatch.Color_ORANGE()),
		cloudwatch.*tableThreshold_Below(jsii.Number(500), cloudwatch.Color_GREEN()),
	},
}))

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

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewTableWidget(&TableWidgetProps{
	// ...

	ShowUnitsInLabel: jsii.Boolean(true),
}))

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

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewTableWidget(&TableWidgetProps{
	// ...

	FullPrecision: jsii.Boolean(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.

var dashboard dashboard
var errorAlarm alarm
var gaugeMetric metric


dashboard.AddWidgets(cloudwatch.NewGaugeWidget(&GaugeWidgetProps{
	Metrics: []iMetric{
		gaugeMetric,
	},
	LeftYAxis: &YAxisProps{
		Min: jsii.Number(0),
		Max: jsii.Number(1000),
	},
}))

Alarm widget

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

var dashboard dashboard
var errorAlarm alarm


dashboard.AddWidgets(cloudwatch.NewAlarmWidget(&AlarmWidgetProps{
	Title: jsii.String("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):

var dashboard dashboard
var visitorCount metric
var purchaseCount metric


dashboard.AddWidgets(cloudwatch.NewSingleValueWidget(&SingleValueWidgetProps{
	Metrics: []iMetric{
		visitorCount,
		purchaseCount,
	},
}))

Show as many digits as can fit, before rounding.

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewSingleValueWidget(&SingleValueWidgetProps{
	Metrics: []iMetric{
	},

	FullPrecision: jsii.Boolean(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

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewSingleValueWidget(&SingleValueWidgetProps{
	Metrics: []iMetric{
	},

	Sparkline: jsii.Boolean(true),
}))

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

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewSingleValueWidget(&SingleValueWidgetProps{
	Metrics: []iMetric{
	},

	Period: awscdk.Duration_Minutes(jsii.Number(15)),
}))

Text widget

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

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewTextWidget(&TextWidgetProps{
	Markdown: jsii.String("# Key Performance Indicators"),
}))

Optionally set the TextWidget background to be transparent

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewTextWidget(&TextWidgetProps{
	Markdown: jsii.String("# Key Performance Indicators"),
	Background: 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.

var dashboard dashboard
var errorAlarm alarm


dashboard.AddWidgets(
cloudwatch.NewAlarmStatusWidget(&AlarmStatusWidgetProps{
	Alarms: []iAlarm{
		errorAlarm,
	},
}))

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

var dashboard dashboard
var errorAlarm alarm


dashboard.AddWidgets(cloudwatch.NewAlarmStatusWidget(&AlarmStatusWidgetProps{
	Title: jsii.String("Errors"),
	Alarms: []iAlarm{
		errorAlarm,
	},
	SortBy: cloudwatch.AlarmStatusWidgetSortBy_STATE_UPDATED_TIMESTAMP,
	States: []alarmState{
		cloudwatch.*alarmState_ALARM,
	},
}))

Query results widget

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

var dashboard dashboard


dashboard.AddWidgets(cloudwatch.NewLogQueryWidget(&LogQueryWidgetProps{
	LogGroupNames: []*string{
		jsii.String("my-log-group"),
	},
	View: cloudwatch.LogQueryVisualizationType_TABLE,
	// The lines will be automatically combined using '\n|'.
	QueryLines: []*string{
		jsii.String("fields @message"),
		jsii.String("filter @message like /Error/"),
	},
}))

Custom widget

A CustomWidget shows the result of an AWS Lambda function:

var dashboard dashboard


// Import or create a lambda function
fn := lambda.Function_FromFunctionArn(dashboard, jsii.String("Function"), jsii.String("arn:aws:lambda:us-east-1:123456789012:function:MyFn"))

dashboard.AddWidgets(cloudwatch.NewCustomWidget(&CustomWidgetProps{
	FunctionArn: fn.FunctionArn,
	Title: jsii.String("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: 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.

var widgetA iWidget
var widgetB iWidget


cloudwatch.NewColumn(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.

var widgetA iWidget
var widgetB iWidget


cloudwatch.NewRow(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 cw "github.com/aws/aws-cdk-go/awscdk"


dashboard := cw.NewDashboard(this, jsii.String("Dash"), &DashboardProps{
	DefaultInterval: awscdk.Duration_Days(jsii.Number(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.

  • 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 "github.com/aws/aws-cdk-go/awscdk"


dashboard := cw.NewDashboard(this, jsii.String("Dash"), &DashboardProps{
	DefaultInterval: awscdk.Duration_Days(jsii.Number(7)),
	Variables: []iVariable{
		cw.NewDashboardVariable(&DashboardVariableOptions{
			Id: jsii.String("region"),
			Type: cw.VariableType_PROPERTY,
			Label: jsii.String("Region"),
			InputType: cw.VariableInputType_RADIO,
			Value: jsii.String("region"),
			Values: cw.Values_FromValues(&VariableValue{
				Label: jsii.String("IAD"),
				Value: jsii.String("us-east-1"),
			}, &VariableValue{
				Label: jsii.String("DUB"),
				Value: jsii.String("us-west-2"),
			}),
			DefaultValue: cw.DefaultValue_Value(jsii.String("us-east-1")),
			Visible: jsii.Boolean(true),
		}),
	},
})

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

import "github.com/aws/aws-cdk-go/awscdk"


dashboard := cw.NewDashboard(this, jsii.String("Dash"), &DashboardProps{
	DefaultInterval: awscdk.Duration_Days(jsii.Number(7)),
	Variables: []iVariable{
		cw.NewDashboardVariable(&DashboardVariableOptions{
			Id: jsii.String("region2"),
			Type: cw.VariableType_PATTERN,
			Label: jsii.String("RegionPattern"),
			InputType: cw.VariableInputType_INPUT,
			Value: jsii.String("us-east-1"),
			DefaultValue: cw.DefaultValue_Value(jsii.String("us-east-1")),
			Visible: jsii.Boolean(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 defaultValue with cw.DefaultValue.FIRST indicates that the default value will be the first value returned from the search.

import "github.com/aws/aws-cdk-go/awscdk"


dashboard := cw.NewDashboard(this, jsii.String("Dash"), &DashboardProps{
	DefaultInterval: awscdk.Duration_Days(jsii.Number(7)),
	Variables: []iVariable{
		cw.NewDashboardVariable(&DashboardVariableOptions{
			Id: jsii.String("functionName"),
			Type: cw.VariableType_PATTERN,
			Label: jsii.String("Function"),
			InputType: cw.VariableInputType_RADIO,
			Value: jsii.String("originalFuncNameInDashboard"),
			// equivalent to cw.Values.fromSearch('{AWS/Lambda,FunctionName} MetricName=\"Duration\"', 'FunctionName')
			Values: cw.Values_FromSearchComponents(&SearchComponents{
				Namespace: jsii.String("AWS/Lambda"),
				Dimensions: []*string{
					jsii.String("FunctionName"),
				},
				MetricName: jsii.String("Duration"),
				PopulateFrom: jsii.String("FunctionName"),
			}),
			DefaultValue: cw.DefaultValue_FIRST(),
			Visible: jsii.Boolean(true),
		}),
	},
})

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

# Functions

Import an existing CloudWatch alarm provided an ARN.
Import an existing CloudWatch alarm provided an Name.
Checks if `x` is a construct.
Returns true if the construct was created by CDK, and false otherwise.
Check whether the given construct is a Resource.
Checks if `x` is a construct.
Returns true if the construct was created by CDK, and false otherwise.
Check whether the given construct is a Resource.
function to join all provided AlarmRules with AND operator.
function to join all provided AlarmRules with OR operator.
function to build Rule Expression for given IAlarm and AlarmState.
function to build TRUE/FALSE intent for Rule Expression.
function to build Rule Expression for given Alarm Rule string.
function to wrap provided AlarmRule in NOT operator.
No description provided by the author
Returns `true` if a construct is a stack element (i.e.
Check whether the given object is a CfnResource.
Checks if `x` is a construct.
No description provided by the author
Returns `true` if a construct is a stack element (i.e.
Check whether the given object is a CfnResource.
Checks if `x` is a construct.
No description provided by the author
Returns `true` if a construct is a stack element (i.e.
Check whether the given object is a CfnResource.
Checks if `x` is a construct.
No description provided by the author
Returns `true` if a construct is a stack element (i.e.
Check whether the given object is a CfnResource.
Checks if `x` is a construct.
No description provided by the author
Returns `true` if a construct is a stack element (i.e.
Check whether the given object is a CfnResource.
Checks if `x` is a construct.
No description provided by the author
Returns `true` if a construct is a stack element (i.e.
Check whether the given object is a CfnResource.
Checks if `x` is a construct.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Import an existing CloudWatch composite alarm provided an ARN.
Import an existing CloudWatch composite alarm provided an Name.
Checks if `x` is a construct.
Returns true if the construct was created by CDK, and false otherwise.
Check whether the given construct is a Resource.
Checks if `x` is a construct.
Returns true if the construct was created by CDK, and false otherwise.
Check whether the given construct is a Resource.
No description provided by the author
Create a default value.
Grant permissions to the given identity to write metrics.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
A shorter alias for `percentile()`.
Percentile indicates the relative standing of a value in a dataset.
Percentile rank (PR) is the percentage of values that meet a fixed threshold.
Shorter alias for `percentileRank()`.
No description provided by the author
No description provided by the author
Shorter alias for `trimmedCount()`.
A shorter alias for `trimmedMean()`.
Trimmed count (TC) is the number of data points in the chosen range for a trimmed mean statistic.
Trimmed mean (TM) is the mean of all values that are between two specified boundaries.
Trimmed sum (TS) is the sum of the values of data points in a chosen range for a trimmed mean statistic.
Shorter alias for `trimmedSum()`.
Winsorized mean (WM) is similar to trimmed mean.
A shorter alias for `winsorizedMean()`.
A threshold for highlighting and coloring cells above the specified value.
A threshold for highlighting and coloring cells below the specified value.
A threshold for highlighting and coloring cells within the specified values.
Create values from a search expression.
Create values from the components of search expression.
Create values from an array of possible variable values.

# Constants

State indicates resource is in ALARM.
State indicates there is not enough data to determine is resource is in ALARM.
State indicates resource is not in ALARM.
Choose DEFAULT to sort them in alphabetical order by alarm name.
Choose STATE_UPDATED_TIMESTAMP to sort them first by alarm state, with alarms in ALARM state first, INSUFFICIENT_DATA alarms next, and OK alarms last.
Choose TIMESTAMP to sort them by the time when the alarms most recently changed state, no matter the current alarm state.
Specified statistic is greater than or equal to the threshold.
Specified statistic is strictly greater than the threshold.
Specified statistic is greater than the anomaly model band.
Specified statistic is lower than or greater than the anomaly model band.
Specified statistic is lower than the anomaly model band.
Specified statistic is less than or equal to the threshold.
Specified statistic is strictly less than the threshold.
Display as a bar graph.
Display as a pie graph.
Display as a line graph.
Legend appears below the graph (default).
Add shading below the annotation.
Add shading above the annotation.
Bar view.
Line view.
Pie view.
Stacked area view.
Table view.
Period of all graphs on the dashboard automatically adapt to the time range of the dashboard.
Period set for each graph will be used.
Add shading above the annotation.
Add shading below the annotation.
Don't add shading.
The value of Sum / SampleCount during the specified period.
The highest value observed during the specified period.
The lowest value observed during the specified period.
The count (number) of data points used for the statistical calculation.
All values submitted for the matching metric added together.
Data points are laid out in columns.
Data points are laid out in rows.
Average of all data points.
Maximum of all data points.
Minimum of all data points.
Sum of all data points.
Solid background.
Transparent background.
Missing data points are treated as breaching the threshold.
The current alarm state is maintained.
The alarm does not consider missing data points when evaluating whether to change state.
Missing data points are treated as being within the threshold.
Bits.
Bits/second (b/s).
Bytes.
Bytes/second (B/s).
Count.
Count/second.
Gigabits.
Gigabits/second (Gb/s).
Gigabytes.
Gigabytes/second (GB/s).
Kilobits.
Kilobits/second (kb/s).
Kilobytes.
Kilobytes/second (kB/s).
Megabits.
Megabits/second (Mb/s).
Megabytes.
Megabytes/second (MB/s).
Microseconds.
Milliseconds.
None.
Percent.
Seconds.
Terabits.
Terabits/second (Tb/s).
Terabytes.
Terabytes/second (TB/s).
Freeform text input box.
A dropdown of pre-defined values, or values filled in from a metric search query.
A set of pre-defined radio buttons, which can also be defined from a metric search query.
A pattern variable is one that changes a regex pattern across the dashboard JSON.
A property variable changes the values of all instances of a property in the list of widgets in the dashboard.
Add shading after the annotation.
Add shading before the annotation.
Don't add shading.

# Structs

Properties for an alarm action.
Properties for Alarms.
Properties for an Alarm Status Widget.
Properties for an AlarmWidget.
Dimension is an embedded property of the `AWS::CloudWatch::Alarm` type.
The `MetricDataQuery` property 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.
The `Metric` property type represents a specific metric.
This structure defines the metric to be returned, along with the statistics, period, and units.
Properties for defining a `CfnAlarm`.
Specifies details about how the anomaly detection model is to be trained, including time ranges to exclude when training and updating the model.
A dimension is a name/value pair that is part of the identity of a metric.
This object includes parameters that you can use to provide information to CloudWatch to help it build more accurate anomaly detection models.
This structure is used in both `GetMetricData` and `PutMetricAlarm` .
Indicates the CloudWatch math expression that provides the time series the anomaly detector uses as input.
Represents a specific metric.
This structure defines the metric to be returned, along with the statistics, period, and units.
Each `Range` specifies one range of days or times to exclude from use for training or updating an anomaly detection model.
Designates the CloudWatch metric and statistic that provides the time series the anomaly detector uses as input.
Properties for defining a `CfnAnomalyDetector`.
Properties for defining a `CfnCompositeAlarm`.
Properties for defining a `CfnDashboard`.
Properties for defining a `CfnInsightRule`.
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.
This structure specifies a list of additional statistics to stream, and the metrics to stream those additional statistics for.
A structure that specifies the metric name and namespace for one metric that is going to have additional statistics included in the stream.
Properties for defining a `CfnMetricStream`.
Options shared by most methods accepting metric options.
Properties for creating a Composite Alarm.
Properties needed to make an alarm from a metric.
The properties for a CustomWidget.
Properties for defining a CloudWatch Dashboard.
Options for {@link DashboardVariable}.
Metric dimension.
Properties for a GaugeWidget.
Properties for a GraphWidget.
Horizontal annotation to be added to a graph.
Properties for a Query widget.
Configurable options for MathExpressions.
Properties for a MathExpression.
Properties of a rendered metric.
Properties for a concrete metric.
Properties of a metric that can be changed.
Properties for a metric.
Properties for a concrete metric.
Basic properties for widgets that display metrics.
Search components for use with {@link Values.fromSearchComponents}.
Properties for a SingleValueWidget.
Props of the spacer.
Properties for TableWidget's summary columns.
Properties for a TableWidget.
Properties for a Text widget.
Example: import "github.com/aws/aws-cdk-go/awscdk" dashboard := cw.NewDashboard(this, jsii.String("Dash"), &DashboardProps{ DefaultInterval: awscdk.Duration_Days(jsii.Number(7)), Variables: []iVariable{ cw.NewDashboardVariable(&DashboardVariableOptions{ Id: jsii.String("region"), Type: cw.VariableType_PROPERTY, Label: jsii.String("Region"), InputType: cw.VariableInputType_RADIO, Value: jsii.String("region"), Values: cw.Values_FromValues(&VariableValue{ Label: jsii.String("IAD"), Value: jsii.String("us-east-1"), }, &VariableValue{ Label: jsii.String("DUB"), Value: jsii.String("us-west-2"), }), DefaultValue: cw.DefaultValue_Value(jsii.String("us-east-1")), Visible: jsii.Boolean(true), }), }, }) .
Vertical annotation to be added to a graph.
Properties for a Y-Axis.

# Interfaces

An alarm on a CloudWatch metric.
The base class for Alarm and CompositeAlarm resources.
Class with static functions to build AlarmRule for Composite Alarms.
A dashboard widget that displays alarms in a grid view.
Display the metric associated with an alarm, including the alarm line.
The `AWS::CloudWatch::Alarm` type specifies an alarm and associates it with the specified metric or metric math expression.
The `AWS::CloudWatch::AnomalyDetector` type specifies an anomaly detection band for a certain metric and statistic.
The `AWS::CloudWatch::CompositeAlarm` type creates or updates a composite alarm.
The `AWS::CloudWatch::Dashboard` resource specifies an Amazon CloudWatch dashboard.
Creates or updates a Contributor Insights rule.
Creates or updates a metric stream.
A set of standard colours that can be used in annotations in a GraphWidget.
A widget that contains other widgets in a vertical column.
A Composite Alarm based on Alarm Rule.
A real CloudWatch widget that has its own fixed size and remembers its position.
A CustomWidget shows the result of a AWS lambda function.
A CloudWatch dashboard.
Dashboard Variable.
Default value for use in {@link DashboardVariableOptions}.
A dashboard gauge widget that displays metrics.
A dashboard widget that displays metrics.
Represents a CloudWatch Alarm.
Interface for objects that can be the targets of CloudWatch alarm actions.
Interface for Alarm Rule.
Interface for metrics.
A single dashboard variable.
A single dashboard widget.
Display query results from Logs Insights.
A math expression built with metric(s) emitted by a service.
A metric emitted by a service.
A widget that contains other widgets in a horizontal row.
A dashboard widget that displays the most recent value for every metric.
A widget that doesn't display anything but takes up space.
Factory functions for standard statistics strings.
Thresholds for highlighting cells in TableWidget.
A dashboard widget that displays metrics.
A dashboard widget that displays MarkDown.
A class for providing values for use with {@link VariableInputType.SELECT} and {@link VariableInputType.RADIO} dashboard variables.

# Type aliases

Enumeration indicates state of Alarm used in building Alarm Rule.
The sort possibilities for AlarmStatusWidgets.
Comparison operator for evaluating alarms.
Types of view.
The position of the legend on a GraphWidget.
Types of view.
Specify the period for graphs when the CloudWatch dashboard loads.
Fill shading options that will be used with a horizontal annotation.
Statistic to use over the aggregation period.
Layout for TableWidget.
Standard table summary columns.
Background types available.
Specify how missing data points are treated during alarm evaluation.
Unit for metric.
Example: import "github.com/aws/aws-cdk-go/awscdk" dashboard := cw.NewDashboard(this, jsii.String("Dash"), &DashboardProps{ DefaultInterval: awscdk.Duration_Days(jsii.Number(7)), Variables: []iVariable{ cw.NewDashboardVariable(&DashboardVariableOptions{ Id: jsii.String("functionName"), Type: cw.VariableType_PATTERN, Label: jsii.String("Function"), InputType: cw.VariableInputType_RADIO, Value: jsii.String("originalFuncNameInDashboard"), // equivalent to cw.Values.fromSearch('{AWS/Lambda,FunctionName} MetricName=\"Duration\"', 'FunctionName') Values: cw.Values_FromSearchComponents(&SearchComponents{ Namespace: jsii.String("AWS/Lambda"), Dimensions: []*string{ jsii.String("FunctionName"), }, MetricName: jsii.String("Duration"), PopulateFrom: jsii.String("FunctionName"), }), DefaultValue: cw.DefaultValue_FIRST(), Visible: jsii.Boolean(true), }), }, }) .
Example: import "github.com/aws/aws-cdk-go/awscdk" dashboard := cw.NewDashboard(this, jsii.String("Dash"), &DashboardProps{ DefaultInterval: awscdk.Duration_Days(jsii.Number(7)), Variables: []iVariable{ cw.NewDashboardVariable(&DashboardVariableOptions{ Id: jsii.String("functionName"), Type: cw.VariableType_PATTERN, Label: jsii.String("Function"), InputType: cw.VariableInputType_RADIO, Value: jsii.String("originalFuncNameInDashboard"), // equivalent to cw.Values.fromSearch('{AWS/Lambda,FunctionName} MetricName=\"Duration\"', 'FunctionName') Values: cw.Values_FromSearchComponents(&SearchComponents{ Namespace: jsii.String("AWS/Lambda"), Dimensions: []*string{ jsii.String("FunctionName"), }, MetricName: jsii.String("Duration"), PopulateFrom: jsii.String("FunctionName"), }), DefaultValue: cw.DefaultValue_FIRST(), Visible: jsii.Boolean(true), }), }, }) .
Fill shading options that will be used with a vertical annotation.