# 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:

TypeScript:

```ts
declare const fn: lambda.Function;

const errors = fn.metricErrors();
```

Python:

```python
# fn: lambda.Function

errors = fn.metric_errors()
```

Java:

```java
Function fn;

Metric errors = fn.metricErrors();
```

C# / .NET:

```csharp
Function fn;

var errors = fn.MetricErrors();
```

Golang:

```go
var fn Function

errors := fn.metricErrors()
```

[`Metric`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) objects to reference any
[published metric](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-services-cloudwatch-metrics.html)
that's not exposed using a convenience method on the CDK construct.
For example:

TypeScript:

```ts
const hostedZone = new route53.HostedZone(this, 'MyHostedZone', { zoneName: "example.org" });
const metric = new cloudwatch.Metric({
  namespace: 'AWS/Route53',
  metricName: 'DNSQueries',
  dimensionsMap: {
    HostedZoneId: hostedZone.hostedZoneId
  }
});
```

Python:

```python
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
    }
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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 }
    }
});
```

Golang:

```go
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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) object to represent it. For example:

TypeScript:

```ts
const metric = new cloudwatch.Metric({
  namespace: 'MyNamespace',
  metricName: 'MyMetric',
  dimensionsMap: {
    ProcessingStep: 'Download'
  }
});
```

Python:

```python
metric = cloudwatch.Metric(
    namespace="MyNamespace",
    metric_name="MyMetric",
    dimensions_map={
        "ProcessingStep": "Download"
    }
)
```

Java:

```java
Metric metric = Metric.Builder.create()
        .namespace("MyNamespace")
        .metricName("MyMetric")
        .dimensionsMap(Map.of(
                "ProcessingStep", "Download"))
        .build();
```

C# / .NET:

```csharp
var metric = new Metric(new MetricProps {
    Namespace = "MyNamespace",
    MetricName = "MyMetric",
    DimensionsMap = new Dictionary<string, string> {
        { "ProcessingStep", "Download" }
    }
});
```

Golang:

```go
metric := cloudwatch.NewMetric(&MetricProps{
	Namespace: jsii.String("MyNamespace"),
	MetricName: jsii.String("MyMetric"),
	DimensionsMap: map[string]*string{
		"ProcessingStep": jsii.String("Download"),
	},
})
```

### Metric ID

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

TypeScript:

```ts
const metric = new cloudwatch.Metric({
  namespace: 'AWS/Lambda',
  metricName: 'Invocations',
  dimensionsMap: {
    FunctionName: 'MyFunction'
  },
  id: 'invocations'
});
```

Python:

```python
metric = cloudwatch.Metric(
    namespace="AWS/Lambda",
    metric_name="Invocations",
    dimensions_map={
        "FunctionName": "MyFunction"
    },
    id="invocations"
)
```

Java:

```java
Metric metric = Metric.Builder.create()
        .namespace("AWS/Lambda")
        .metricName("Invocations")
        .dimensionsMap(Map.of(
                "FunctionName", "MyFunction"))
        .id("invocations")
        .build();
```

C# / .NET:

```csharp
var metric = new Metric(new MetricProps {
    Namespace = "AWS/Lambda",
    MetricName = "Invocations",
    DimensionsMap = new Dictionary<string, string> {
        { "FunctionName", "MyFunction" }
    },
    Id = "invocations"
});
```

Golang:

```go
metric := cloudwatch.NewMetric(&MetricProps{
	Namespace: jsii.String("AWS/Lambda"),
	MetricName: jsii.String("Invocations"),
	DimensionsMap: map[string]*string{
		"FunctionName": jsii.String("MyFunction"),
	},
	Id: jsii.String("invocations"),
})
```

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

### Metric Visible
Metrics can be hidden from dashboard graphs using the `visible` property:

TypeScript:

```ts
declare const fn: lambda.Function;

const metric = fn.metricErrors({
  visible: false
});
```

Python:

```python
# fn: lambda.Function

metric = fn.metric_errors(
    visible=False
)
```

Java:

```java
Function fn;

Metric metric = fn.metricErrors(MetricOptions.builder()
        .visible(false)
        .build());
```

C# / .NET:

```csharp
Function fn;

var metric = fn.MetricErrors(new MetricOptions {
    Visible = false
});
```

Golang:

```go
var fn Function

metric := fn.metricErrors(&MetricOptions{
	Visible: jsii.Boolean(false),
})
```

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

### Metric Math

Math expressions are supported by instantiating the [`MathExpression`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MathExpression.html) class.
For example, a math expression that sums two other metrics looks like this:

TypeScript:

```ts
declare const fn: lambda.Function;

const allProblems = new cloudwatch.MathExpression({
  expression: "errors + throttles",
  usingMetrics: {
    errors: fn.metricErrors(),
    throttles: fn.metricThrottles(),
  }
});
```

Python:

```python
# fn: lambda.Function

all_problems = cloudwatch.MathExpression(
    expression="errors + throttles",
    using_metrics={
        "errors": fn.metric_errors(),
        "throttles": fn.metric_throttles()
    }
)
```

Java:

```java
Function fn;

MathExpression allProblems = MathExpression.Builder.create()
        .expression("errors + throttles")
        .usingMetrics(Map.of(
                "errors", fn.metricErrors(),
                "throttles", fn.metricThrottles()))
        .build();
```

C# / .NET:

```csharp
Function fn;

var allProblems = new MathExpression(new MathExpressionProps {
    Expression = "errors + throttles",
    UsingMetrics = new Dictionary<string, IMetric> {
        { "errors", fn.MetricErrors() },
        { "throttles", fn.MetricThrottles() }
    }
});
```

Golang:

```go
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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MathExpression.html) objects like any other metric, including using
them in other math expressions:

TypeScript:

```ts
declare const fn: lambda.Function;
declare const allProblems: cloudwatch.MathExpression;

const problemPercentage = new cloudwatch.MathExpression({
  expression: "(problems / invocations) * 100",
  usingMetrics: {
    problems: allProblems,
    invocations: fn.metricInvocations()
  }
});
```

Python:

```python
# fn: lambda.Function
# all_problems: cloudwatch.MathExpression

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

Java:

```java
Function fn;
MathExpression allProblems;

MathExpression problemPercentage = MathExpression.Builder.create()
        .expression("(problems / invocations) * 100")
        .usingMetrics(Map.of(
                "problems", allProblems,
                "invocations", fn.metricInvocations()))
        .build();
```

C# / .NET:

```csharp
Function fn;
MathExpression allProblems;

var problemPercentage = new MathExpression(new MathExpressionProps {
    Expression = "(problems / invocations) * 100",
    UsingMetrics = new Dictionary<string, IMetric> {
        { "problems", allProblems },
        { "invocations", fn.MetricInvocations() }
    }
});
```

Golang:

```go
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(),
	},
})
```

Like [`Metric`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html), a [`MathExpression`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MathExpression.html) can be hidden from a graph by setting
`visible: false`. This keeps the expression available (for example, as an input
to another expression) while removing its line from the widget:

TypeScript:

```ts
declare const fn: lambda.Function;
declare const dashboard: cloudwatch.Dashboard;

const errorRate = new cloudwatch.MathExpression({
  expression: "errors / invocations * 100",
  usingMetrics: {
    errors: fn.metricErrors(),
    invocations: fn.metricInvocations(),
  },
  visible: false,
});

dashboard.addWidgets(new cloudwatch.GraphWidget({
  left: [fn.metricInvocations(), errorRate],
}));
```

Python:

```python
# fn: lambda.Function
# dashboard: cloudwatch.Dashboard

error_rate = cloudwatch.MathExpression(
    expression="errors / invocations * 100",
    using_metrics={
        "errors": fn.metric_errors(),
        "invocations": fn.metric_invocations()
    },
    visible=False
)

dashboard.add_widgets(cloudwatch.GraphWidget(
    left=[fn.metric_invocations(), error_rate]
))
```

Java:

```java
Function fn;
Dashboard dashboard;

MathExpression errorRate = MathExpression.Builder.create()
        .expression("errors / invocations * 100")
        .usingMetrics(Map.of(
                "errors", fn.metricErrors(),
                "invocations", fn.metricInvocations()))
        .visible(false)
        .build();

dashboard.addWidgets(GraphWidget.Builder.create()
        .left(List.of(fn.metricInvocations(), errorRate))
        .build());
```

C# / .NET:

```csharp
Function fn;
Dashboard dashboard;

var errorRate = new MathExpression(new MathExpressionProps {
    Expression = "errors / invocations * 100",
    UsingMetrics = new Dictionary<string, IMetric> {
        { "errors", fn.MetricErrors() },
        { "invocations", fn.MetricInvocations() }
    },
    Visible = false
});

dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
    Left = new [] { fn.MetricInvocations(), errorRate }
}));
```

Golang:

```go
var fn Function
var dashboard Dashboard

errorRate := cloudwatch.NewMathExpression(&MathExpressionProps{
	Expression: jsii.String("errors / invocations * 100"),
	UsingMetrics: map[string]IMetric{
		"errors": fn.metricErrors(),
		"invocations": fn.metricInvocations(),
	},
	Visible: jsii.Boolean(false),
})

dashboard.AddWidgets(cloudwatch.NewGraphWidget(&GraphWidgetProps{
	Left: []IMetric{
		fn.metricInvocations(),
		errorRate,
	},
}))
```

The array form of `MAX`, `MIN`, `AVG` and `SUM` (for example `MAX([m1, m2])`)
only accepts time series. CloudWatch rejects an array that mixes a metric with a
scalar number, so an alarm using it fails to deploy.
See [Metric math syntax and functions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/using-metric-math.html#metric-math-syntax-functions-list)
for the arguments each function accepts.

### Metric ID Usage in Math Expressions

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

TypeScript:

```ts
declare const fn: lambda.Function;

const invocations = fn.metricInvocations({
  id: 'lambda_invocations',
});

const errors = fn.metricErrors({
  id: 'lambda_errors',
});
```

Python:

```python
# fn: lambda.Function

invocations = fn.metric_invocations(
    id="lambda_invocations"
)

errors = fn.metric_errors(
    id="lambda_errors"
)
```

Java:

```java
Function fn;

Metric invocations = fn.metricInvocations(MetricOptions.builder()
        .id("lambda_invocations")
        .build());

Metric errors = fn.metricErrors(MetricOptions.builder()
        .id("lambda_errors")
        .build());
```

C# / .NET:

```csharp
Function fn;

var invocations = fn.MetricInvocations(new MetricOptions {
    Id = "lambda_invocations"
});

var errors = fn.MetricErrors(new MetricOptions {
    Id = "lambda_errors"
});
```

Golang:

```go
var fn Function

invocations := fn.metricInvocations(&MetricOptions{
	Id: jsii.String("lambda_invocations"),
})

errors := fn.metricErrors(&MetricOptions{
	Id: jsii.String("lambda_errors"),
})
```

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

TypeScript:

```ts
const errorRate = new cloudwatch.MathExpression({
  expression: 'lambda_errors / lambda_invocations * 100',
  label: 'Error Rate (%)',
});
```

Python:

```python
error_rate = cloudwatch.MathExpression(
    expression="lambda_errors / lambda_invocations * 100",
    label="Error Rate (%)"
)
```

Java:

```java
MathExpression errorRate = MathExpression.Builder.create()
        .expression("lambda_errors / lambda_invocations * 100")
        .label("Error Rate (%)")
        .build();
```

C# / .NET:

```csharp
var errorRate = new MathExpression(new MathExpressionProps {
    Expression = "lambda_errors / lambda_invocations * 100",
    Label = "Error Rate (%)"
});
```

Golang:

```go
errorRate := cloudwatch.NewMathExpression(&MathExpressionProps{
	Expression: jsii.String("lambda_errors / lambda_invocations * 100"),
	Label: jsii.String("Error Rate (%)"),
})
```

### Search Expressions

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

#### Using SearchExpression Class

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

TypeScript:

```ts
const cpuUtilization = new cloudwatch.SearchExpression({
  expression: "SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 900)",
  label: 'EC2 CPU Utilization',
  color: '#ff7f0e',
});
```

Python:

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

Java:

```java
SearchExpression cpuUtilization = SearchExpression.Builder.create()
        .expression("SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 900)")
        .label("EC2 CPU Utilization")
        .color("#ff7f0e")
        .build();
```

C# / .NET:

```csharp
var cpuUtilization = new SearchExpression(new SearchExpressionProps {
    Expression = "SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 900)",
    Label = "EC2 CPU Utilization",
    Color = "#ff7f0e"
});
```

Golang:

```go
cpuUtilization := cloudwatch.NewSearchExpression(&SearchExpressionProps{
	Expression: jsii.String("SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 900)"),
	Label: jsii.String("EC2 CPU Utilization"),
	Color: jsii.String("#ff7f0e"),
})
```

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.

TypeScript:

```ts
const crossAccountSearch = new cloudwatch.SearchExpression({
  expression: "SEARCH('{AWS/Lambda,FunctionName} MetricName=\"Invocations\"', 'Sum', 300)",
  searchAccount: '123456789012',
  searchRegion: 'us-west-2',
  label: 'Production Lambda Invocations',
});
```

Python:

```python
cross_account_search = cloudwatch.SearchExpression(
    expression="SEARCH('{AWS/Lambda,FunctionName} MetricName=\"Invocations\"', 'Sum', 300)",
    search_account="123456789012",
    search_region="us-west-2",
    label="Production Lambda Invocations"
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
var crossAccountSearch = new SearchExpression(new SearchExpressionProps {
    Expression = "SEARCH('{AWS/Lambda,FunctionName} MetricName=\"Invocations\"', 'Sum', 300)",
    SearchAccount = "123456789012",
    SearchRegion = "us-west-2",
    Label = "Production Lambda Invocations"
});
```

Golang:

```go
crossAccountSearch := cloudwatch.NewSearchExpression(&SearchExpressionProps{
	Expression: jsii.String("SEARCH('{AWS/Lambda,FunctionName} MetricName=\"Invocations\"', 'Sum', 300)"),
	SearchAccount: jsii.String("123456789012"),
	SearchRegion: jsii.String("us-west-2"),
	Label: jsii.String("Production Lambda Invocations"),
})
```

Like [`Metric`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) and [`MathExpression`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MathExpression.html), a [`SearchExpression`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SearchExpression.html) can be hidden from a
graph by setting `visible: false`. The time series stay on the widget without
being rendered, so they can still be toggled on in the CloudWatch console:

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

const hiddenSearch = new cloudwatch.SearchExpression({
  expression: "SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 300)",
  label: 'EC2 CPU Utilization',
  visible: false,
});

dashboard.addWidgets(new cloudwatch.GraphWidget({
  left: [hiddenSearch],
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

hidden_search = cloudwatch.SearchExpression(
    expression="SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 300)",
    label="EC2 CPU Utilization",
    visible=False
)

dashboard.add_widgets(cloudwatch.GraphWidget(
    left=[hidden_search]
))
```

Java:

```java
Dashboard dashboard;

SearchExpression hiddenSearch = SearchExpression.Builder.create()
        .expression("SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 300)")
        .label("EC2 CPU Utilization")
        .visible(false)
        .build();

dashboard.addWidgets(GraphWidget.Builder.create()
        .left(List.of(hiddenSearch))
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

var hiddenSearch = new SearchExpression(new SearchExpressionProps {
    Expression = "SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 300)",
    Label = "EC2 CPU Utilization",
    Visible = false
});

dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
    Left = new [] { hiddenSearch }
}));
```

Golang:

```go
var dashboard Dashboard

hiddenSearch := cloudwatch.NewSearchExpression(&SearchExpressionProps{
	Expression: jsii.String("SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 300)"),
	Label: jsii.String("EC2 CPU Utilization"),
	Visible: jsii.Boolean(false),
})

dashboard.AddWidgets(cloudwatch.NewGraphWidget(&GraphWidgetProps{
	Left: []IMetric{
		hiddenSearch,
	},
}))
```

### 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:

TypeScript:

```ts
declare const fn: lambda.Function;

const minuteErrorRate = fn.metricErrors({
  statistic: cloudwatch.Stats.AVERAGE,
  period: Duration.minutes(1),
  label: 'Lambda failure rate'
});
```

Python:

```python
# fn: lambda.Function

minute_error_rate = fn.metric_errors(
    statistic=cloudwatch.Stats.AVERAGE,
    period=Duration.minutes(1),
    label="Lambda failure rate"
)
```

Java:

```java
Function fn;

Metric minuteErrorRate = fn.metricErrors(MetricOptions.builder()
        .statistic(Stats.AVERAGE)
        .period(Duration.minutes(1))
        .label("Lambda failure rate")
        .build());
```

C# / .NET:

```csharp
Function fn;

var minuteErrorRate = fn.MetricErrors(new MetricOptions {
    Statistic = Stats.AVERAGE,
    Period = Duration.Minutes(1),
    Label = "Lambda failure rate"
});
```

Golang:

```go
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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) objects, we default to
> aggregating using `Sum`, which will be the same for both metrics types. If you
> happen to know the Metric you want to alarm on makes sense as a rate
> (`Average`) you can always choose to change the statistic.

### Available Aggregation Statistics

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

| Statistic                |    Short format     |                 Long format                  | Factory name         |
| ------------------------ | :-----------------: | :------------------------------------------: | -------------------- |
| SampleCount (n)          |         ❌          |                      ❌                      | `Stats.SAMPLE_COUNT` |
| Average (avg)            |         ❌          |                      ❌                      | `Stats.AVERAGE`      |
| Sum                      |         ❌          |                      ❌                      | `Stats.SUM`          |
| Minimum (min)            |         ❌          |                      ❌                      | `Stats.MINIMUM`      |
| Maximum (max)            |         ❌          |                      ❌                      | `Stats.MAXIMUM`      |
| Interquartile mean (IQM) |         ❌          |                      ❌                      | `Stats.IQM`          |
| Percentile (p)           |        `p99`        |                      ❌                      | `Stats.p(99)`        |
| Winsorized mean (WM)     | `wm99` = `WM(:99%)` | `WM(x:y) \| WM(x%:y%) \| 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](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Statistics-definitions.html).

TypeScript:

```ts
declare const hostedZone: route53.HostedZone;

new cloudwatch.Metric({
  namespace: 'AWS/Route53',
  metricName: 'DNSQueries',
  dimensionsMap: {
    HostedZoneId: hostedZone.hostedZoneId
  },
  statistic: cloudwatch.Stats.SAMPLE_COUNT,
  period: Duration.minutes(5)
});

new cloudwatch.Metric({
  namespace: 'AWS/Route53',
  metricName: 'DNSQueries',
  dimensionsMap: {
    HostedZoneId: hostedZone.hostedZoneId
  },
  statistic: cloudwatch.Stats.p(99),
  period: Duration.minutes(5)
});

new cloudwatch.Metric({
  namespace: 'AWS/Route53',
  metricName: 'DNSQueries',
  dimensionsMap: {
    HostedZoneId: hostedZone.hostedZoneId
  },
  statistic: 'TS(7.5%:90%)',
  period: Duration.minutes(5)
});
```

Python:

```python
# hosted_zone: route53.HostedZone

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

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

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

Java:

```java
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();
```

C# / .NET:

```csharp
HostedZone hostedZone;

new Metric(new MetricProps {
    Namespace = "AWS/Route53",
    MetricName = "DNSQueries",
    DimensionsMap = new Dictionary<string, string> {
        { "HostedZoneId", hostedZone.HostedZoneId }
    },
    Statistic = Stats.SAMPLE_COUNT,
    Period = Duration.Minutes(5)
});

new Metric(new MetricProps {
    Namespace = "AWS/Route53",
    MetricName = "DNSQueries",
    DimensionsMap = new Dictionary<string, string> {
        { "HostedZoneId", hostedZone.HostedZoneId }
    },
    Statistic = Stats.P(99),
    Period = Duration.Minutes(5)
});

new Metric(new MetricProps {
    Namespace = "AWS/Route53",
    MetricName = "DNSQueries",
    DimensionsMap = new Dictionary<string, string> {
        { "HostedZoneId", hostedZone.HostedZoneId }
    },
    Statistic = "TS(7.5%:90%)",
    Period = Duration.Minutes(5)
});
```

Golang:

```go
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](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/graph-dynamic-labels.html)
to show summary information about the displayed time series
in the legend. For example, if you use:

TypeScript:

```ts
declare const fn: lambda.Function;

const minuteErrorRate = fn.metricErrors({
  statistic: cloudwatch.Stats.SUM,
  period: Duration.hours(1),

  // Show the maximum hourly error count in the legend
  label: '[max: ${MAX}] Lambda failure rate',
});
```

Python:

```python
# fn: lambda.Function

minute_error_rate = fn.metric_errors(
    statistic=cloudwatch.Stats.SUM,
    period=Duration.hours(1),

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

Java:

```java
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());
```

C# / .NET:

```csharp
Function fn;

var minuteErrorRate = fn.MetricErrors(new MetricOptions {
    Statistic = Stats.SUM,
    Period = Duration.Hours(1),

    // Show the maximum hourly error count in the legend
    Label = "[max: ${MAX}] Lambda failure rate"
});
```

Golang:

```go
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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Alarm.html)
object, passing the [`Metric`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) object to set the alarm on:

TypeScript:

```ts
declare const fn: lambda.Function;

new cloudwatch.Alarm(this, 'Alarm', {
  metric: fn.metricErrors(),
  threshold: 100,
  evaluationPeriods: 2,
});
```

Python:

```python
# fn: lambda.Function

cloudwatch.Alarm(self, "Alarm",
    metric=fn.metric_errors(),
    threshold=100,
    evaluation_periods=2
)
```

Java:

```java
Function fn;

Alarm.Builder.create(this, "Alarm")
        .metric(fn.metricErrors())
        .threshold(100)
        .evaluationPeriods(2)
        .build();
```

C# / .NET:

```csharp
Function fn;

new Alarm(this, "Alarm", new AlarmProps {
    Metric = fn.MetricErrors(),
    Threshold = 100,
    EvaluationPeriods = 2
});
```

Golang:

```go
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()`:

TypeScript:

```ts
declare const fn: lambda.Function;

fn.metricErrors().createAlarm(this, 'Alarm', {
  threshold: 100,
  evaluationPeriods: 2,
});
```

Python:

```python
# fn: lambda.Function

fn.metric_errors().create_alarm(self, "Alarm",
    threshold=100,
    evaluation_periods=2
)
```

Java:

```java
Function fn;

fn.metricErrors().createAlarm(this, "Alarm", CreateAlarmOptions.builder()
        .threshold(100)
        .evaluationPeriods(2)
        .build());
```

C# / .NET:

```csharp
Function fn;

fn.MetricErrors().CreateAlarm(this, "Alarm", new CreateAlarmOptions {
    Threshold = 100,
    EvaluationPeriods = 2
});
```

Golang:

```go
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](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Cross-Account-Cross-Region.html) in CloudWatch. Then, set the `account` property in the [`Metric`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) 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 the [`Metrics` field of the Alarm resource](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudwatch-alarm.html#cfn-cloudwatch-alarm-metrics). If we use the `Metrics` field, the CloudWatch event that is
  used to evaluate the Alarm doesn't have a `SampleCount` field anymore ("[When CloudWatch evaluates alarms, periods are aggregated into single data points](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Create-alarm-on-metric-math-expression.html)"). The result is that the Alarm cannot evaluate at all.
- Create a cross-Region alarm ([source](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Cross-Account-Cross-Region.html)).

### 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:

TypeScript:

```ts
import * as cw_actions from 'aws-cdk-lib/aws-cloudwatch-actions';
declare const alarm: cloudwatch.Alarm;

const topic = new sns.Topic(this, 'Topic');
alarm.addAlarmAction(new cw_actions.SnsAction(topic));
```

Python:

```python
import aws_cdk.aws_cloudwatch_actions as cw_actions
# alarm: cloudwatch.Alarm

topic = sns.Topic(self, "Topic")
alarm.add_alarm_action(cw_actions.SnsAction(topic))
```

Java:

```java
import software.amazon.awscdk.services.cloudwatch.actions.*;
Alarm alarm;

Topic topic = new Topic(this, "Topic");
alarm.addAlarmAction(new SnsAction(topic));
```

C# / .NET:

```csharp
using Amazon.CDK.AWS.CloudWatch.Actions;
Alarm alarm;

var topic = new Topic(this, "Topic");
alarm.AddAlarmAction(new SnsAction(topic));
```

Golang:

```go
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](https://aws.amazon.com/about-aws/whats-new/2020/03/amazon-cloudwatch-now-allows-you-to-combine-multiple-alarms/)
can be created from existing Alarm resources.

TypeScript:

```ts
declare const alarm1: cloudwatch.Alarm;
declare const alarm2: cloudwatch.Alarm;
declare const alarm3: cloudwatch.Alarm;
declare const alarm4: cloudwatch.Alarm;

const 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)),
    // AT_LEAST with count: at least 2 of these alarms must be in ALARM state
    cloudwatch.AlarmRule.atLeast(cloudwatch.AlarmState.ALARM, {
      operands: [alarm1, alarm2, alarm3],
      threshold: cloudwatch.AtLeastThreshold.count(2),
    }),
    // AT_LEAST with percentage and NOT: at least 60% must NOT be in OK state
    cloudwatch.AlarmRule.atLeastNot(cloudwatch.AlarmState.OK, {
      operands: [alarm1, alarm2, alarm3],
      threshold: cloudwatch.AtLeastThreshold.percentage(60),
    }),
  ),
  cloudwatch.AlarmRule.fromBoolean(false),
);

new cloudwatch.CompositeAlarm(this, 'MyAwesomeCompositeAlarm', {
  alarmRule,
});
```

Python:

```python
# alarm1: cloudwatch.Alarm
# alarm2: cloudwatch.Alarm
# alarm3: cloudwatch.Alarm
# alarm4: cloudwatch.Alarm

alarm_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)),
        # AT_LEAST with count: at least 2 of these alarms must be in ALARM state
        cloudwatch.AlarmRule.at_least(cloudwatch.AlarmState.ALARM,
            operands=[alarm1, alarm2, alarm3],
            threshold=cloudwatch.AtLeastThreshold.count(2)
        ),
        # AT_LEAST with percentage and NOT: at least 60% must NOT be in OK state
        cloudwatch.AlarmRule.at_least_not(cloudwatch.AlarmState.OK,
            operands=[alarm1, alarm2, alarm3],
            threshold=cloudwatch.AtLeastThreshold.percentage(60)
        )),
    cloudwatch.AlarmRule.from_boolean(False))

cloudwatch.CompositeAlarm(self, "MyAwesomeCompositeAlarm",
    alarm_rule=alarm_rule
)
```

Java:

```java
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.atLeast(AlarmState.ALARM, AtLeastOptions.builder()
        .operands(List.of(alarm1, alarm2, alarm3))
        .threshold(AtLeastThreshold.count(2))
        .build()), AlarmRule.atLeastNot(AlarmState.OK, AtLeastOptions.builder()
        .operands(List.of(alarm1, alarm2, alarm3))
        .threshold(AtLeastThreshold.percentage(60))
        .build())), AlarmRule.fromBoolean(false));

CompositeAlarm.Builder.create(this, "MyAwesomeCompositeAlarm")
        .alarmRule(alarmRule)
        .build();
```

C# / .NET:

```csharp
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.AtLeast(AlarmState.ALARM, new AtLeastOptions {
    Operands = new [] { alarm1, alarm2, alarm3 },
    Threshold = AtLeastThreshold.Count(2)
}), AlarmRule.AtLeastNot(AlarmState.OK, new AtLeastOptions {
    Operands = new [] { alarm1, alarm2, alarm3 },
    Threshold = AtLeastThreshold.Percentage(60)
})), AlarmRule.FromBoolean(false));

new CompositeAlarm(this, "MyAwesomeCompositeAlarm", new CompositeAlarmProps {
    AlarmRule = alarmRule
});
```

Golang:

```go
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_AtLeast(cloudwatch.AlarmState_ALARM, &AtLeastOptions{
	Operands: []IAlarm{
		alarm1,
		alarm2,
		alarm3,
	},
	Threshold: cloudwatch.AtLeastThreshold_Count(jsii.Number(2)),
}), cloudwatch.AlarmRule_AtLeastNot(cloudwatch.AlarmState_OK, &AtLeastOptions{
	Operands: []IAlarm{
		alarm1,
		alarm2,
		alarm3,
	},
	Threshold: cloudwatch.AtLeastThreshold_Percentage(jsii.Number(60)),
})), 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](https://www.amazonaws.cn/en/new/2022/amazon-cloudwatch-supports-composite-alarm-actions-suppression/).

TypeScript:

```ts
declare const alarm1: cloudwatch.Alarm;
declare const alarm2: cloudwatch.Alarm;
declare const onAlarmAction: cloudwatch.IAlarmAction;
declare const onOkAction: cloudwatch.IAlarmAction;
declare const actionsSuppressor: cloudwatch.Alarm;

const alarmRule = cloudwatch.AlarmRule.anyOf(alarm1, alarm2);

const myCompositeAlarm = new cloudwatch.CompositeAlarm(this, 'MyAwesomeCompositeAlarm', {
  alarmRule,
  actionsSuppressor,
});
myCompositeAlarm.addAlarmAction(onAlarmAction);
myCompositeAlarm.addOkAction(onOkAction);
```

Python:

```python
# alarm1: cloudwatch.Alarm
# alarm2: cloudwatch.Alarm
# on_alarm_action: cloudwatch.IAlarmAction
# on_ok_action: cloudwatch.IAlarmAction
# actions_suppressor: cloudwatch.Alarm

alarm_rule = cloudwatch.AlarmRule.any_of(alarm1, alarm2)

my_composite_alarm = cloudwatch.CompositeAlarm(self, "MyAwesomeCompositeAlarm",
    alarm_rule=alarm_rule,
    actions_suppressor=actions_suppressor
)
my_composite_alarm.add_alarm_action(on_alarm_action)
my_composite_alarm.add_ok_action(on_ok_action)
```

Java:

```java
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);
```

C# / .NET:

```csharp
Alarm alarm1;
Alarm alarm2;
IAlarmAction onAlarmAction;
IAlarmAction onOkAction;
Alarm actionsSuppressor;

var alarmRule = AlarmRule.AnyOf(alarm1, alarm2);

var myCompositeAlarm = new CompositeAlarm(this, "MyAwesomeCompositeAlarm", new CompositeAlarmProps {
    AlarmRule = alarmRule,
    ActionsSuppressor = actionsSuppressor
});
myCompositeAlarm.AddAlarmAction(onAlarmAction);
myCompositeAlarm.AddOkAction(onOkAction);
```

Golang:

```go
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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AnomalyDetectionAlarm.html) class for convenience, which takes care
of building the right metric math expression and passing in a magic value for
the treshold for you:

TypeScript:

```ts
// Create a metric
const metric = new cloudwatch.Metric({
  namespace: 'AWS/EC2',
  metricName: 'CPUUtilization',
  statistic: 'Average',
  period: Duration.hours(1), // Alarm will use the metric's period
});

// Create an anomaly detection alarm
const alarm = new cloudwatch.AnomalyDetectionAlarm(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: cloudwatch.ComparisonOperator.LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD,
  alarmDescription: 'Alarm when metric is outside the expected band',
});
```

Python:

```python
# Create a metric
metric = cloudwatch.Metric(
    namespace="AWS/EC2",
    metric_name="CPUUtilization",
    statistic="Average",
    period=Duration.hours(1)
)

# Create an anomaly detection alarm
alarm = cloudwatch.AnomalyDetectionAlarm(self, "AnomalyAlarm",
    metric=metric,
    evaluation_periods=1,

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

Java:

```java
// 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();
```

C# / .NET:

```csharp
// Create a metric
var metric = new Metric(new MetricProps {
    Namespace = "AWS/EC2",
    MetricName = "CPUUtilization",
    Statistic = "Average",
    Period = Duration.Hours(1)
});

// Create an anomaly detection alarm
var alarm = new AnomalyDetectionAlarm(this, "AnomalyAlarm", new AnomalyDetectionAlarmProps {
    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"
});
```

Golang:

```go
// Create a metric
metric := cloudwatch.NewMetric(&MetricProps{
	Namespace: jsii.String("AWS/EC2"),
	MetricName: jsii.String("CPUUtilization"),
	Statistic: jsii.String("Average"),
	Period: awscdk.Duration_Hours(jsii.Number(1)),
})

// Create an anomaly detection alarm
alarm := cloudwatch.NewAnomalyDetectionAlarm(this, jsii.String("AnomalyAlarm"), &AnomalyDetectionAlarmProps{
	Metric: metric,
	EvaluationPeriods: jsii.Number(1),

	// Number of standard deviations for the band (default: 2)
	StdDevs: jsii.Number(2),
	// Alarm outside on either side of the band, or just below or above it (default: outside)
	ComparisonOperator: cloudwatch.ComparisonOperator_LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD,
	AlarmDescription: jsii.String("Alarm when metric is outside the expected band"),
})
```

### Comparison Operators for Anomaly Detection

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

- `LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD`: Alarm when the metric is outside the band, on either side of it
- `GREATER_THAN_UPPER_THRESHOLD`: Alarm only when the metric is above the band
- `LESS_THAN_LOWER_THRESHOLD`: Alarm only when the metric is below the band

For more information on anomaly detection in CloudWatch, see the [AWS documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Anomaly_Detection.html).

## PromQL Alarms

PromQL alarms evaluate a [PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/) instant query against metrics ingested through the CloudWatch OTLP endpoint on a recurring schedule. All matching time series returned by the query are considered breaching, and each is tracked independently as a _contributor_.

### How PromQL Alarms Differ from Standard CloudWatch Alarms

The existing [`Alarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Alarm.html) construct is designed around the standard CloudWatch alarm model: a metric, a comparison operator, a threshold, and evaluation periods. PromQL alarms have a fundamentally different configuration model:

- Instead of using alarm condition (threshold + comparison), all matching time series returned by the PromQL alarm query are considered to be breaching.
- Instead of `evaluationPeriods` and `period`, PromQL alarms use `evaluationInterval`, `pendingPeriod`, and `recoveryPeriod`.
- PromQL alarms do not use `MetricName`, `Namespace`, [`Statistic`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Statistic.html), `Dimensions`, or `Threshold` properties.
- PromQL alarms only work with metrics ingested through the CloudWatch OTLP endpoint. Standard CloudWatch namespace metrics (e.g., `AWS/EC2`, `AWS/Lambda`) are not queryable via PromQL.

### Creating a PromQL Alarm

TypeScript:

```ts
new cloudwatch.PromQLAlarm(this, 'HighCpuAlarm', {
  alarmName: 'HighCpuAlarm',
  alarmDescription: 'Alarm when average CPU exceeds 80%',
  query: 'avg(cpu_utilization_percent) > 80',
  evaluationInterval: Duration.seconds(60),
});
```

Python:

```python
cloudwatch.PromQLAlarm(self, "HighCpuAlarm",
    alarm_name="HighCpuAlarm",
    alarm_description="Alarm when average CPU exceeds 80%",
    query="avg(cpu_utilization_percent) > 80",
    evaluation_interval=Duration.seconds(60)
)
```

Java:

```java
PromQLAlarm.Builder.create(this, "HighCpuAlarm")
        .alarmName("HighCpuAlarm")
        .alarmDescription("Alarm when average CPU exceeds 80%")
        .query("avg(cpu_utilization_percent) > 80")
        .evaluationInterval(Duration.seconds(60))
        .build();
```

C# / .NET:

```csharp
new PromQLAlarm(this, "HighCpuAlarm", new PromQLAlarmProps {
    AlarmName = "HighCpuAlarm",
    AlarmDescription = "Alarm when average CPU exceeds 80%",
    Query = "avg(cpu_utilization_percent) > 80",
    EvaluationInterval = Duration.Seconds(60)
});
```

Golang:

```go
cloudwatch.NewPromQLAlarm(this, jsii.String("HighCpuAlarm"), &PromQLAlarmProps{
	AlarmName: jsii.String("HighCpuAlarm"),
	AlarmDescription: jsii.String("Alarm when average CPU exceeds 80%"),
	Query: jsii.String("avg(cpu_utilization_percent) > 80"),
	EvaluationInterval: awscdk.Duration_Seconds(jsii.Number(60)),
})
```

### Pending and Recovery Periods

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

TypeScript:

```ts
new cloudwatch.PromQLAlarm(this, 'HighLatencyAlarm', {
  alarmDescription: 'P99 latency exceeds 500ms for 5 minutes',
  query: 'histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m])) > 0.5',
  evaluationInterval: Duration.seconds(60),
  pendingPeriod: Duration.seconds(300),
  recoveryPeriod: Duration.seconds(600),
});
```

Python:

```python
cloudwatch.PromQLAlarm(self, "HighLatencyAlarm",
    alarm_description="P99 latency exceeds 500ms for 5 minutes",
    query="histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m])) > 0.5",
    evaluation_interval=Duration.seconds(60),
    pending_period=Duration.seconds(300),
    recovery_period=Duration.seconds(600)
)
```

Java:

```java
PromQLAlarm.Builder.create(this, "HighLatencyAlarm")
        .alarmDescription("P99 latency exceeds 500ms for 5 minutes")
        .query("histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m])) > 0.5")
        .evaluationInterval(Duration.seconds(60))
        .pendingPeriod(Duration.seconds(300))
        .recoveryPeriod(Duration.seconds(600))
        .build();
```

C# / .NET:

```csharp
new PromQLAlarm(this, "HighLatencyAlarm", new PromQLAlarmProps {
    AlarmDescription = "P99 latency exceeds 500ms for 5 minutes",
    Query = "histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m])) > 0.5",
    EvaluationInterval = Duration.Seconds(60),
    PendingPeriod = Duration.Seconds(300),
    RecoveryPeriod = Duration.Seconds(600)
});
```

Golang:

```go
cloudwatch.NewPromQLAlarm(this, jsii.String("HighLatencyAlarm"), &PromQLAlarmProps{
	AlarmDescription: jsii.String("P99 latency exceeds 500ms for 5 minutes"),
	Query: jsii.String("histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m])) > 0.5"),
	EvaluationInterval: awscdk.Duration_Seconds(jsii.Number(60)),
	PendingPeriod: awscdk.Duration_*Seconds(jsii.Number(300)),
	RecoveryPeriod: awscdk.Duration_*Seconds(jsii.Number(600)),
})
```

### Adding Actions

[`PromQLAlarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.PromQLAlarm.html) extends [`AlarmBase`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmBase.html), so you can add alarm, OK, and insufficient-data actions the same way as standard alarms:

TypeScript:

```ts
import * as cloudwatch_actions from 'aws-cdk-lib/aws-cloudwatch-actions';

declare const topic: sns.Topic;

const alarm = new cloudwatch.PromQLAlarm(this, 'ServiceDownAlarm', {
  query: 'up == 0',
  evaluationInterval: Duration.seconds(60),
  pendingPeriod: Duration.seconds(300),
  recoveryPeriod: Duration.seconds(300),
});

alarm.addAlarmAction(new cloudwatch_actions.SnsAction(topic));
alarm.addOkAction(new cloudwatch_actions.SnsAction(topic));
```

Python:

```python
import aws_cdk.aws_cloudwatch_actions as cloudwatch_actions

# topic: sns.Topic

alarm = cloudwatch.PromQLAlarm(self, "ServiceDownAlarm",
    query="up == 0",
    evaluation_interval=Duration.seconds(60),
    pending_period=Duration.seconds(300),
    recovery_period=Duration.seconds(300)
)

alarm.add_alarm_action(cloudwatch_actions.SnsAction(topic))
alarm.add_ok_action(cloudwatch_actions.SnsAction(topic))
```

Java:

```java
import software.amazon.awscdk.services.cloudwatch.actions.*;

Topic topic;

PromQLAlarm alarm = PromQLAlarm.Builder.create(this, "ServiceDownAlarm")
        .query("up == 0")
        .evaluationInterval(Duration.seconds(60))
        .pendingPeriod(Duration.seconds(300))
        .recoveryPeriod(Duration.seconds(300))
        .build();

alarm.addAlarmAction(new SnsAction(topic));
alarm.addOkAction(new SnsAction(topic));
```

C# / .NET:

```csharp
using Amazon.CDK.AWS.CloudWatch.Actions;

Topic topic;

var alarm = new PromQLAlarm(this, "ServiceDownAlarm", new PromQLAlarmProps {
    Query = "up == 0",
    EvaluationInterval = Duration.Seconds(60),
    PendingPeriod = Duration.Seconds(300),
    RecoveryPeriod = Duration.Seconds(300)
});

alarm.AddAlarmAction(new SnsAction(topic));
alarm.AddOkAction(new SnsAction(topic));
```

Golang:

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

var topic Topic

alarm := cloudwatch.NewPromQLAlarm(this, jsii.String("ServiceDownAlarm"), &PromQLAlarmProps{
	Query: jsii.String("up == 0"),
	EvaluationInterval: awscdk.Duration_Seconds(jsii.Number(60)),
	PendingPeriod: awscdk.Duration_*Seconds(jsii.Number(300)),
	RecoveryPeriod: awscdk.Duration_*Seconds(jsii.Number(300)),
})

alarm.AddAlarmAction(cloudwatch_actions.NewSnsAction(topic))
alarm.AddOkAction(cloudwatch_actions.NewSnsAction(topic))
```

### Importing an Existing PromQL Alarm

TypeScript:

```ts
const importedByArn = cloudwatch.PromQLAlarm.fromPromQLAlarmArn(
  this, 'ImportedAlarm',
  'arn:aws:cloudwatch:us-east-1:123456789012:alarm:MyPromQLAlarm',
);

const importedByName = cloudwatch.PromQLAlarm.fromPromQLAlarmName(
  this, 'ImportedByName',
  'MyPromQLAlarm',
);
```

Python:

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

imported_by_name = cloudwatch.PromQLAlarm.from_prom_ql_alarm_name(self, "ImportedByName", "MyPromQLAlarm")
```

Java:

```java
IAlarm importedByArn = PromQLAlarm.fromPromQLAlarmArn(this, "ImportedAlarm", "arn:aws:cloudwatch:us-east-1:123456789012:alarm:MyPromQLAlarm");

IAlarm importedByName = PromQLAlarm.fromPromQLAlarmName(this, "ImportedByName", "MyPromQLAlarm");
```

C# / .NET:

```csharp
var importedByArn = PromQLAlarm.FromPromQLAlarmArn(this, "ImportedAlarm", "arn:aws:cloudwatch:us-east-1:123456789012:alarm:MyPromQLAlarm");

var importedByName = PromQLAlarm.FromPromQLAlarmName(this, "ImportedByName", "MyPromQLAlarm");
```

Golang:

```go
importedByArn := cloudwatch.PromQLAlarm_FromPromQLAlarmArn(this, jsii.String("ImportedAlarm"), jsii.String("arn:aws:cloudwatch:us-east-1:123456789012:alarm:MyPromQLAlarm"))

importedByName := cloudwatch.PromQLAlarm_FromPromQLAlarmName(this, jsii.String("ImportedByName"), jsii.String("MyPromQLAlarm"))
```

### Using in Composite Alarms

Since [`PromQLAlarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.PromQLAlarm.html) implements [`IAlarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IAlarm.html), it can be used in composite alarm rules alongside standard alarms:

TypeScript:

```ts
declare const promqlAlarm: cloudwatch.PromQLAlarm;
declare const standardAlarm: cloudwatch.Alarm;

new cloudwatch.CompositeAlarm(this, 'CompositeAlarm', {
  alarmRule: cloudwatch.AlarmRule.allOf(promqlAlarm, standardAlarm),
});
```

Python:

```python
# promql_alarm: cloudwatch.PromQLAlarm
# standard_alarm: cloudwatch.Alarm

cloudwatch.CompositeAlarm(self, "CompositeAlarm",
    alarm_rule=cloudwatch.AlarmRule.all_of(promql_alarm, standard_alarm)
)
```

Java:

```java
PromQLAlarm promqlAlarm;
Alarm standardAlarm;

CompositeAlarm.Builder.create(this, "CompositeAlarm")
        .alarmRule(AlarmRule.allOf(promqlAlarm, standardAlarm))
        .build();
```

C# / .NET:

```csharp
PromQLAlarm promqlAlarm;
Alarm standardAlarm;

new CompositeAlarm(this, "CompositeAlarm", new CompositeAlarmProps {
    AlarmRule = AlarmRule.AllOf(promqlAlarm, standardAlarm)
});
```

Golang:

```go
var promqlAlarm PromQLAlarm
var standardAlarm Alarm

cloudwatch.NewCompositeAlarm(this, jsii.String("CompositeAlarm"), &CompositeAlarmProps{
	AlarmRule: cloudwatch.AlarmRule_AllOf(promqlAlarm, standardAlarm),
})
```

## Alarm Mute Rules

Alarm Mute Rules is a CloudWatch feature that provides you a mechanism to
automatically mute alarm actions during predefined time windows.
When you create a mute rule, you define specific time periods and target
alarms whose actions will be muted.
CloudWatch will continue monitoring and evaluating alarm states while preventing
unwanted notifications or automated alarm actions during expected operational events.

TypeScript:

```ts
declare const alarm1: cloudwatch.Alarm;
declare const alarm2: cloudwatch.Alarm;

const alarmMuteRule = new cloudwatch.AlarmMuteRule(this, 'AlarmMuteRule', {
  alarms: [alarm1],
  // Defines the mute period begins at 0:00 everyday in UTC
  schedule: cloudwatch.ScheduleExpression.cron({ minute: '0', hour: '0' }),
  // Specifies the mute rule lasts 1 hour.
  duration: Duration.hours(1),
})

// The mute target can be added after construction.
alarmMuteRule.addAlarm(alarm2);
```

Python:

```python
# alarm1: cloudwatch.Alarm
# alarm2: cloudwatch.Alarm

alarm_mute_rule = cloudwatch.AlarmMuteRule(self, "AlarmMuteRule",
    alarms=[alarm1],
    # Defines the mute period begins at 0:00 everyday in UTC
    schedule=cloudwatch.ScheduleExpression.cron(minute="0", hour="0"),
    # Specifies the mute rule lasts 1 hour.
    duration=Duration.hours(1)
)

# The mute target can be added after construction.
alarm_mute_rule.add_alarm(alarm2)
```

Java:

```java
Alarm alarm1;
Alarm alarm2;

AlarmMuteRule alarmMuteRule = AlarmMuteRule.Builder.create(this, "AlarmMuteRule")
        .alarms(List.of(alarm1))
        // Defines the mute period begins at 0:00 everyday in UTC
        .schedule(ScheduleExpression.cron(CronOptions.builder().minute("0").hour("0").build()))
        // Specifies the mute rule lasts 1 hour.
        .duration(Duration.hours(1))
        .build();

// The mute target can be added after construction.
alarmMuteRule.addAlarm(alarm2);
```

C# / .NET:

```csharp
Alarm alarm1;
Alarm alarm2;

var alarmMuteRule = new AlarmMuteRule(this, "AlarmMuteRule", new AlarmMuteRuleProps {
    Alarms = new [] { alarm1 },
    // Defines the mute period begins at 0:00 everyday in UTC
    Schedule = ScheduleExpression.Cron(new CronOptions { Minute = "0", Hour = "0" }),
    // Specifies the mute rule lasts 1 hour.
    Duration = Duration.Hours(1)
});

// The mute target can be added after construction.
alarmMuteRule.AddAlarm(alarm2);
```

Golang:

```go
var alarm1 Alarm
var alarm2 Alarm

alarmMuteRule := cloudwatch.NewAlarmMuteRule(this, jsii.String("AlarmMuteRule"), &AlarmMuteRuleProps{
	Alarms: []IAlarmRef{
		alarm1,
	},
	// Defines the mute period begins at 0:00 everyday in UTC
	Schedule: cloudwatch.ScheduleExpression_Cron(&CronOptions{
		Minute: jsii.String("0"),
		Hour: jsii.String("0"),
	}),
	// Specifies the mute rule lasts 1 hour.
	Duration: awscdk.Duration_Hours(jsii.Number(1)),
})

// The mute target can be added after construction.
alarmMuteRule.AddAlarm(alarm2)
```

For more information on alarm mute rules, see the [AWS documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/alarm-mute-rules.html).

## 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.GraphWidget.html) -- shows any number of metrics on both the left and right
  vertical axes.
- [`AlarmWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmWidget.html) -- shows the graph and alarm line for a single alarm.
- [`SingleValueWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SingleValueWidget.html) -- shows the current value of a set of metrics.
- [`TextWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TextWidget.html) -- shows some static Markdown.
- [`AlarmStatusWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmStatusWidget.html) -- 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:

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;
declare const executionCountMetric: cloudwatch.Metric;
declare const errorCountMetric: cloudwatch.Metric;

dashboard.addWidgets(new cloudwatch.GraphWidget({
  title: "Executions vs error rate",

  left: [executionCountMetric],

  right: [errorCountMetric.with({
    statistic: cloudwatch.Stats.AVERAGE,
    label: "Error rate",
    color: cloudwatch.Color.GREEN,
  })]
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard
# execution_count_metric: cloudwatch.Metric
# error_count_metric: cloudwatch.Metric

dashboard.add_widgets(cloudwatch.GraphWidget(
    title="Executions vs error rate",

    left=[execution_count_metric],

    right=[error_count_metric.with(
        statistic=cloudwatch.Stats.AVERAGE,
        label="Error rate",
        color=cloudwatch.Color.GREEN
    )]
))
```

Java:

```java
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());
```

C# / .NET:

```csharp
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 = Stats.AVERAGE,
        Label = "Error rate",
        Color = Color.GREEN
    }) }
}));
```

Golang:

```go
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.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.GraphWidget({
  // ...

  leftAnnotations: [
    { value: 1800, label: Duration.minutes(30).toHumanString(), color: cloudwatch.Color.RED, },
    { value: 3600, label: '1 hour', color: '#2ca02c', }
  ],
  verticalAnnotations: [
    { date: '2022-10-19T00:00:00Z', label: 'Deployment', color: cloudwatch.Color.RED, }
  ]
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.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")
    ],
    vertical_annotations=[cloudwatch.VerticalAnnotation(date="2022-10-19T00:00:00Z", label="Deployment", color=cloudwatch.Color.RED)
    ]
))
```

Java:

```java
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());
```

C# / .NET:

```csharp
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" } },
    VerticalAnnotations = new [] { new VerticalAnnotation { Date = "2022-10-19T00:00:00Z", Label = "Deployment", Color = Color.RED } }
}));
```

Golang:

```go
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.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.GraphWidget({
  // ...

  legendPosition: cloudwatch.LegendPosition.RIGHT,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.GraphWidget(
    # ...

    legend_position=cloudwatch.LegendPosition.RIGHT
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(GraphWidget.Builder.create()
        // ...

        .legendPosition(LegendPosition.RIGHT)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
    // ...

    LegendPosition = LegendPosition.RIGHT
}));
```

Golang:

```go
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.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.GraphWidget({
  // ...

  liveData: true,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.GraphWidget(
    # ...

    live_data=True
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(GraphWidget.Builder.create()
        // ...

        .liveData(true)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
    // ...

    LiveData = true
}));
```

Golang:

```go
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'.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.GraphWidget({
  // ...

  view: cloudwatch.GraphWidgetView.BAR,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.GraphWidget(
    # ...

    view=cloudwatch.GraphWidgetView.BAR
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(GraphWidget.Builder.create()
        // ...

        .view(GraphWidgetView.BAR)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
    // ...

    View = GraphWidgetView.BAR
}));
```

Golang:

```go
var dashboard Dashboard

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

	View: cloudwatch.GraphWidgetView_BAR,
}))
```

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`.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.GraphWidget({
  // ...

  view: cloudwatch.GraphWidgetView.PIE,
  displayLabelsOnChart: true,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.GraphWidget(
    # ...

    view=cloudwatch.GraphWidgetView.PIE,
    display_labels_on_chart=True
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(GraphWidget.Builder.create()
        // ...

        .view(GraphWidgetView.PIE)
        .displayLabelsOnChart(true)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
    // ...

    View = GraphWidgetView.PIE,
    DisplayLabelsOnChart = true
}));
```

Golang:

```go
var dashboard Dashboard

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

	View: cloudwatch.GraphWidgetView_PIE,
	DisplayLabelsOnChart: jsii.Boolean(true),
}))
```

The `start` and `end` properties can be used to specify the time range for each graph widget independently from those of the dashboard.
The parameters can be specified at [`GraphWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.GraphWidget.html), [`GaugeWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.GaugeWidget.html), and [`SingleValueWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SingleValueWidget.html).

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.GraphWidget({
  // ...

  start: '-P7D',
  end: '2018-12-17T06:00:00.000Z',
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.GraphWidget(
    # ...

    start="-P7D",
    end="2018-12-17T06:00:00.000Z"
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(GraphWidget.Builder.create()
        // ...

        .start("-P7D")
        .end("2018-12-17T06:00:00.000Z")
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
    // ...

    Start = "-P7D",
    End = "2018-12-17T06:00:00.000Z"
}));
```

Golang:

```go
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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TableWidget.html) can display any number of metrics in tabular form.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;
declare const executionCountMetric: cloudwatch.Metric;

dashboard.addWidgets(new cloudwatch.TableWidget({
  title: "Executions",
  metrics: [executionCountMetric],
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard
# execution_count_metric: cloudwatch.Metric

dashboard.add_widgets(cloudwatch.TableWidget(
    title="Executions",
    metrics=[execution_count_metric]
))
```

Java:

```java
Dashboard dashboard;
Metric executionCountMetric;

dashboard.addWidgets(TableWidget.Builder.create()
        .title("Executions")
        .metrics(List.of(executionCountMetric))
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;
Metric executionCountMetric;

dashboard.AddWidgets(new TableWidget(new TableWidgetProps {
    Title = "Executions",
    Metrics = new [] { executionCountMetric }
}));
```

Golang:

```go
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.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.TableWidget({
  // ...

  layout: cloudwatch.TableLayout.VERTICAL,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.TableWidget(
    # ...

    layout=cloudwatch.TableLayout.VERTICAL
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(TableWidget.Builder.create()
        // ...

        .layout(TableLayout.VERTICAL)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new TableWidget(new TableWidgetProps {
    // ...

    Layout = TableLayout.VERTICAL
}));
```

Golang:

```go
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).

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.TableWidget({
  // ...

  summary: {
    columns: [cloudwatch.TableSummaryColumn.AVERAGE],
    hideNonSummaryColumns: true,
    sticky: true,
  },
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.TableWidget(
    # ...

    summary=cloudwatch.TableSummaryProps(
        columns=[cloudwatch.TableSummaryColumn.AVERAGE],
        hide_non_summary_columns=True,
        sticky=True
    )
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(TableWidget.Builder.create()
        // ...

        .summary(TableSummaryProps.builder()
                .columns(List.of(TableSummaryColumn.AVERAGE))
                .hideNonSummaryColumns(true)
                .sticky(true)
                .build())
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new TableWidget(new TableWidgetProps {
    // ...

    Summary = new TableSummaryProps {
        Columns = new [] { TableSummaryColumn.AVERAGE },
        HideNonSummaryColumns = true,
        Sticky = true
    }
}));
```

Golang:

```go
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.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.TableWidget({
  // ...

  thresholds: [
    cloudwatch.TableThreshold.above(1000, cloudwatch.Color.RED),
    cloudwatch.TableThreshold.between(500, 1000, cloudwatch.Color.ORANGE),
    cloudwatch.TableThreshold.below(500, cloudwatch.Color.GREEN),
  ],
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.TableWidget(
    # ...

    thresholds=[
        cloudwatch.TableThreshold.above(1000, cloudwatch.Color.RED),
        cloudwatch.TableThreshold.between(500, 1000, cloudwatch.Color.ORANGE),
        cloudwatch.TableThreshold.below(500, cloudwatch.Color.GREEN)
    ]
))
```

Java:

```java
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());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new TableWidget(new TableWidgetProps {
    // ...

    Thresholds = new [] { TableThreshold.Above(1000, Color.RED), TableThreshold.Between(500, 1000, Color.ORANGE), TableThreshold.Below(500, Color.GREEN) }
}));
```

Golang:

```go
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.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.TableWidget({
  // ...

  showUnitsInLabel: true,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.TableWidget(
    # ...

    show_units_in_label=True
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(TableWidget.Builder.create()
        // ...

        .showUnitsInLabel(true)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new TableWidget(new TableWidgetProps {
    // ...

    ShowUnitsInLabel = true
}));
```

Golang:

```go
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.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.TableWidget({
  // ...

  fullPrecision: true,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.TableWidget(
    # ...

    full_precision=True
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(TableWidget.Builder.create()
        // ...

        .fullPrecision(true)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new TableWidget(new TableWidgetProps {
    // ...

    FullPrecision = true
}));
```

Golang:

```go
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.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;
declare const errorAlarm: cloudwatch.Alarm;
declare const gaugeMetric: cloudwatch.Metric;

dashboard.addWidgets(new cloudwatch.GaugeWidget({
  metrics: [gaugeMetric],
  leftYAxis: {
    min: 0,
    max: 1000,
  }
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard
# error_alarm: cloudwatch.Alarm
# gauge_metric: cloudwatch.Metric

dashboard.add_widgets(cloudwatch.GaugeWidget(
    metrics=[gauge_metric],
    left_y_axis=cloudwatch.YAxisProps(
        min=0,
        max=1000
    )
))
```

Java:

```java
Dashboard dashboard;
Alarm errorAlarm;
Metric gaugeMetric;

dashboard.addWidgets(GaugeWidget.Builder.create()
        .metrics(List.of(gaugeMetric))
        .leftYAxis(YAxisProps.builder()
                .min(0)
                .max(1000)
                .build())
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;
Alarm errorAlarm;
Metric gaugeMetric;

dashboard.AddWidgets(new GaugeWidget(new GaugeWidgetProps {
    Metrics = new [] { gaugeMetric },
    LeftYAxis = new YAxisProps {
        Min = 0,
        Max = 1000
    }
}));
```

Golang:

```go
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:

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;
declare const errorAlarm: cloudwatch.Alarm;

dashboard.addWidgets(new cloudwatch.AlarmWidget({
  title: "Errors",
  alarm: errorAlarm,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard
# error_alarm: cloudwatch.Alarm

dashboard.add_widgets(cloudwatch.AlarmWidget(
    title="Errors",
    alarm=error_alarm
))
```

Java:

```java
Dashboard dashboard;
Alarm errorAlarm;

dashboard.addWidgets(AlarmWidget.Builder.create()
        .title("Errors")
        .alarm(errorAlarm)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;
Alarm errorAlarm;

dashboard.AddWidgets(new AlarmWidget(new AlarmWidgetProps {
    Title = "Errors",
    Alarm = errorAlarm
}));
```

Golang:

```go
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):

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;
declare const visitorCount: cloudwatch.Metric;
declare const purchaseCount: cloudwatch.Metric;

dashboard.addWidgets(new cloudwatch.SingleValueWidget({
  metrics: [visitorCount, purchaseCount],
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard
# visitor_count: cloudwatch.Metric
# purchase_count: cloudwatch.Metric

dashboard.add_widgets(cloudwatch.SingleValueWidget(
    metrics=[visitor_count, purchase_count]
))
```

Java:

```java
Dashboard dashboard;
Metric visitorCount;
Metric purchaseCount;

dashboard.addWidgets(SingleValueWidget.Builder.create()
        .metrics(List.of(visitorCount, purchaseCount))
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;
Metric visitorCount;
Metric purchaseCount;

dashboard.AddWidgets(new SingleValueWidget(new SingleValueWidgetProps {
    Metrics = new [] { visitorCount, purchaseCount }
}));
```

Golang:

```go
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.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.SingleValueWidget({
  metrics: [ /* ... */ ],

  fullPrecision: true,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.SingleValueWidget(
    metrics=[],

    full_precision=True
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(SingleValueWidget.Builder.create()
        .metrics(List.of())

        .fullPrecision(true)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new SingleValueWidget(new SingleValueWidgetProps {
    Metrics = new [] {  },

    FullPrecision = true
}));
```

Golang:

```go
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`

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.SingleValueWidget({
  metrics: [ /* ... */ ],

  sparkline: true,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.SingleValueWidget(
    metrics=[],

    sparkline=True
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(SingleValueWidget.Builder.create()
        .metrics(List.of())

        .sparkline(true)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new SingleValueWidget(new SingleValueWidgetProps {
    Metrics = new [] {  },

    Sparkline = true
}));
```

Golang:

```go
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:

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.SingleValueWidget({
  metrics: [ /* ... */ ],

  period: Duration.minutes(15),
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.SingleValueWidget(
    metrics=[],

    period=Duration.minutes(15)
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(SingleValueWidget.Builder.create()
        .metrics(List.of())

        .period(Duration.minutes(15))
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new SingleValueWidget(new SingleValueWidgetProps {
    Metrics = new [] {  },

    Period = Duration.Minutes(15)
}));
```

Golang:

```go
var dashboard Dashboard

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

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

The widget can show live data published within the last minute that has not been fully aggregated.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.SingleValueWidget({
  metrics: [ /* ... */ ],

  liveData: true,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.SingleValueWidget(
    metrics=[],

    live_data=True
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(SingleValueWidget.Builder.create()
        .metrics(List.of())

        .liveData(true)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new SingleValueWidget(new SingleValueWidgetProps {
    Metrics = new [] {  },

    LiveData = true
}));
```

Golang:

```go
var dashboard Dashboard

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

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

### Text widget

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

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.TextWidget({
  markdown: '# Key Performance Indicators'
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.TextWidget(
    markdown="# Key Performance Indicators"
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(TextWidget.Builder.create()
        .markdown("# Key Performance Indicators")
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new TextWidget(new TextWidgetProps {
    Markdown = "# Key Performance Indicators"
}));
```

Golang:

```go
var dashboard Dashboard

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

Optionally set the TextWidget background to be transparent

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.TextWidget({
  markdown: '# Key Performance Indicators',
  background: cloudwatch.TextWidgetBackground.TRANSPARENT
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.TextWidget(
    markdown="# Key Performance Indicators",
    background=cloudwatch.TextWidgetBackground.TRANSPARENT
))
```

Java:

```java
Dashboard dashboard;

dashboard.addWidgets(TextWidget.Builder.create()
        .markdown("# Key Performance Indicators")
        .background(TextWidgetBackground.TRANSPARENT)
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new TextWidget(new TextWidgetProps {
    Markdown = "# Key Performance Indicators",
    Background = TextWidgetBackground.TRANSPARENT
}));
```

Golang:

```go
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.

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;
declare const errorAlarm: cloudwatch.Alarm;

dashboard.addWidgets(
  new cloudwatch.AlarmStatusWidget({
    alarms: [errorAlarm],
  })
);
```

Python:

```python
# dashboard: cloudwatch.Dashboard
# error_alarm: cloudwatch.Alarm

dashboard.add_widgets(
    cloudwatch.AlarmStatusWidget(
        alarms=[error_alarm]
    ))
```

Java:

```java
Dashboard dashboard;
Alarm errorAlarm;

dashboard.addWidgets(
AlarmStatusWidget.Builder.create()
        .alarms(List.of(errorAlarm))
        .build());
```

C# / .NET:

```csharp
Dashboard dashboard;
Alarm errorAlarm;

dashboard.AddWidgets(
new AlarmStatusWidget(new AlarmStatusWidgetProps {
    Alarms = new [] { errorAlarm }
}));
```

Golang:

```go
var dashboard Dashboard
var errorAlarm Alarm

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

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

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;
declare const errorAlarm: cloudwatch.Alarm;

dashboard.addWidgets(new cloudwatch.AlarmStatusWidget({
  title: "Errors",
  alarms: [errorAlarm],
  sortBy: cloudwatch.AlarmStatusWidgetSortBy.STATE_UPDATED_TIMESTAMP,
  states: [cloudwatch.AlarmState.ALARM],
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard
# error_alarm: cloudwatch.Alarm

dashboard.add_widgets(cloudwatch.AlarmStatusWidget(
    title="Errors",
    alarms=[error_alarm],
    sort_by=cloudwatch.AlarmStatusWidgetSortBy.STATE_UPDATED_TIMESTAMP,
    states=[cloudwatch.AlarmState.ALARM]
))
```

Java:

```java
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());
```

C# / .NET:

```csharp
Dashboard dashboard;
Alarm errorAlarm;

dashboard.AddWidgets(new AlarmStatusWidget(new AlarmStatusWidgetProps {
    Title = "Errors",
    Alarms = new [] { errorAlarm },
    SortBy = AlarmStatusWidgetSortBy.STATE_UPDATED_TIMESTAMP,
    States = new [] { AlarmState.ALARM }
}));
```

Golang:

```go
var dashboard Dashboard
var errorAlarm Alarm

dashboard.AddWidgets(cloudwatch.NewAlarmStatusWidget(&AlarmStatusWidgetProps{
	Title: jsii.String("Errors"),
	Alarms: []IAlarmRef{
		errorAlarm,
	},
	SortBy: cloudwatch.AlarmStatusWidgetSortBy_STATE_UPDATED_TIMESTAMP,
	States: []AlarmState{
		cloudwatch.AlarmState_ALARM,
	},
}))
```

### Query results widget

A [`LogQueryWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.LogQueryWidget.html) shows the results of a query from Logs Insights:

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.LogQueryWidget({
  logGroupNames: ['my-log-group'],
  view: cloudwatch.LogQueryVisualizationType.TABLE,
  // The lines will be automatically combined using '\n|'.
  queryLines: [
    'fields @message',
    'filter @message like /Error/',
  ]
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.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/"
    ]
))
```

Java:

```java
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());
```

C# / .NET:

```csharp
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/" }
}));
```

Golang:

```go
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/"),
	},
}))
```

Log Insights QL is the default query language. You may specify an [alternate query language: OpenSearch PPL or SQL](https://aws.amazon.com/blogs/aws/new-amazon-cloudwatch-and-amazon-opensearch-service-launch-an-integrated-analytics-experience/), if desired:

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.LogQueryWidget({
  logGroupNames: ['my-log-group'],
  view: cloudwatch.LogQueryVisualizationType.TABLE,
  queryString: "SELECT count(*) as count FROM 'my-log-group'",
  queryLanguage: cloudwatch.LogQueryLanguage.SQL,
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.LogQueryWidget(
    log_group_names=["my-log-group"],
    view=cloudwatch.LogQueryVisualizationType.TABLE,
    query_string="SELECT count(*) as count FROM 'my-log-group'",
    query_language=cloudwatch.LogQueryLanguage.SQL
))
```

Java:

```java
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());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new LogQueryWidget(new LogQueryWidgetProps {
    LogGroupNames = new [] { "my-log-group" },
    View = LogQueryVisualizationType.TABLE,
    QueryString = "SELECT count(*) as count FROM 'my-log-group'",
    QueryLanguage = LogQueryLanguage.SQL
}));
```

Golang:

```go
var dashboard Dashboard

dashboard.AddWidgets(cloudwatch.NewLogQueryWidget(&LogQueryWidgetProps{
	LogGroupNames: []*string{
		jsii.String("my-log-group"),
	},
	View: cloudwatch.LogQueryVisualizationType_TABLE,
	QueryString: jsii.String("SELECT count(*) as count FROM 'my-log-group'"),
	QueryLanguage: cloudwatch.LogQueryLanguage_SQL,
}))
```

### Custom widget

A [`CustomWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CustomWidget.html) shows the result of an AWS Lambda function:

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

// Import or create a lambda function
const fn = lambda.Function.fromFunctionArn(
  dashboard,
  'Function',
  'arn:aws:lambda:us-east-1:123456789012:function:MyFn',
);

dashboard.addWidgets(new cloudwatch.CustomWidget({
  functionArn: fn.functionArn,
  title: 'My lambda baked widget',
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

# Import or create a lambda function
fn = 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"
))
```

Java:

```java
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());
```

C# / .NET:

```csharp
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"
}));
```

Golang:

```go
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](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/add_custom_widget_dashboard.html).

### 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Column.html): stack two or more widgets vertically.
- [`Row`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Row.html): lay out two or more widgets horizontally.
- [`Spacer`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Spacer.html): 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.

TypeScript:

```ts
declare const widgetA: cloudwatch.IWidget;
declare const widgetB: cloudwatch.IWidget;

new cloudwatch.Column(widgetA, widgetB);
```

Python:

```python
# widget_a: cloudwatch.IWidget
# widget_b: cloudwatch.IWidget

cloudwatch.Column(widget_a, widget_b)
```

Java:

```java
IWidget widgetA;
IWidget widgetB;

new Column(widgetA, widgetB);
```

C# / .NET:

```csharp
IWidget widgetA;
IWidget widgetB;

new Column(widgetA, widgetB);
```

Golang:

```go
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.

TypeScript:

```ts
declare const widgetA: cloudwatch.IWidget;
declare const widgetB: cloudwatch.IWidget;

new cloudwatch.Row(widgetA, widgetB);
```

Python:

```python
# widget_a: cloudwatch.IWidget
# widget_b: cloudwatch.IWidget

cloudwatch.Row(widget_a, widget_b)
```

Java:

```java
IWidget widgetA;
IWidget widgetB;

new Row(widgetA, widgetB);
```

C# / .NET:

```csharp
IWidget widgetA;
IWidget widgetB;

new Row(widgetA, widgetB);
```

Golang:

```go
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 (e.g. 7 days) as `Duration.days(7)`.

TypeScript:

```ts
import * as cw from 'aws-cdk-lib/aws-cloudwatch';

const dashboard = new cw.Dashboard(this, 'Dash', {
  defaultInterval: Duration.days(7),
});
```

Python:

```python
import aws_cdk.aws_cloudwatch as cw

dashboard = cw.Dashboard(self, "Dash",
    default_interval=Duration.days(7)
)
```

Java:

```java
import software.amazon.awscdk.services.cloudwatch.*;

Dashboard dashboard = Dashboard.Builder.create(this, "Dash")
        .defaultInterval(Duration.days(7))
        .build();
```

C# / .NET:

```csharp
using Amazon.CDK.AWS.CloudWatch;

var dashboard = new Dashboard(this, "Dash", new DashboardProps {
    DefaultInterval = Duration.Days(7)
});
```

Golang:

```go
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](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_dashboard_variables.html)

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:

TypeScript:

```ts
import * as cw from 'aws-cdk-lib/aws-cloudwatch';

const dashboard = new cw.Dashboard(this, 'Dash', {
  defaultInterval: Duration.days(7),
  variables: [new cw.DashboardVariable({
    id: 'region',
    type: cw.VariableType.PROPERTY,
    label: 'Region',
    inputType: cw.VariableInputType.RADIO,
    value: 'region',
    values: cw.Values.fromValues({ label: 'IAD', value: 'us-east-1' }, { label: 'DUB', value: 'us-west-2' }),
    defaultValue: cw.DefaultValue.value('us-east-1'),
    visible: true,
  })],
});
```

Python:

```python
import aws_cdk.aws_cloudwatch as cw

dashboard = cw.Dashboard(self, "Dash",
    default_interval=Duration.days(7),
    variables=[cw.DashboardVariable(
        id="region",
        type=cw.VariableType.PROPERTY,
        label="Region",
        input_type=cw.VariableInputType.RADIO,
        value="region",
        values=cw.Values.from_values(cw.VariableValue(label="IAD", value="us-east-1"), label="DUB", value="us-west-2"),
        default_value=cw.DefaultValue.value("us-east-1"),
        visible=True
    )]
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
using Amazon.CDK.AWS.CloudWatch;

var dashboard = new Dashboard(this, "Dash", new DashboardProps {
    DefaultInterval = Duration.Days(7),
    Variables = new [] { new DashboardVariable(new DashboardVariableOptions {
        Id = "region",
        Type = VariableType.PROPERTY,
        Label = "Region",
        InputType = VariableInputType.RADIO,
        Value = "region",
        Values = Values.FromValues(new VariableValue { Label = "IAD", Value = "us-east-1" }, new VariableValue { Label = "DUB", Value = "us-west-2" }),
        DefaultValue = DefaultValue.Value("us-east-1"),
        Visible = true
    }) }
});
```

Golang:

```go
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**

TypeScript:

```ts
import * as cw from 'aws-cdk-lib/aws-cloudwatch';

const dashboard = new cw.Dashboard(this, 'Dash', {
  defaultInterval: Duration.days(7),
  variables: [new cw.DashboardVariable({
    id: 'region2',
    type: cw.VariableType.PATTERN,
    label: 'RegionPattern',
    inputType: cw.VariableInputType.INPUT,
    value: 'us-east-1',
    defaultValue: cw.DefaultValue.value('us-east-1'),
    visible: true,
  })],
});
```

Python:

```python
import aws_cdk.aws_cloudwatch as cw

dashboard = cw.Dashboard(self, "Dash",
    default_interval=Duration.days(7),
    variables=[cw.DashboardVariable(
        id="region2",
        type=cw.VariableType.PATTERN,
        label="RegionPattern",
        input_type=cw.VariableInputType.INPUT,
        value="us-east-1",
        default_value=cw.DefaultValue.value("us-east-1"),
        visible=True
    )]
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
using Amazon.CDK.AWS.CloudWatch;

var dashboard = new Dashboard(this, "Dash", new DashboardProps {
    DefaultInterval = Duration.Days(7),
    Variables = new [] { new DashboardVariable(new DashboardVariableOptions {
        Id = "region2",
        Type = VariableType.PATTERN,
        Label = "RegionPattern",
        InputType = VariableInputType.INPUT,
        Value = "us-east-1",
        DefaultValue = DefaultValue.Value("us-east-1"),
        Visible = true
    }) }
});
```

Golang:

```go
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.

TypeScript:

```ts
import * as cw from 'aws-cdk-lib/aws-cloudwatch';

const dashboard = new cw.Dashboard(this, 'Dash', {
  defaultInterval: Duration.days(7),
  variables: [new cw.DashboardVariable({
    id: 'functionName',
    type: cw.VariableType.PATTERN,
    label: 'Function',
    inputType: cw.VariableInputType.RADIO,
    value: 'originalFuncNameInDashboard',
    // equivalent to cw.Values.fromSearch('{AWS/Lambda,FunctionName} MetricName=\"Duration\"', 'FunctionName')
    values: cw.Values.fromSearchComponents({
      namespace: 'AWS/Lambda',
      dimensions: ['FunctionName'],
      metricName: 'Duration',
      populateFrom: 'FunctionName',
    }),
    defaultValue: cw.DefaultValue.FIRST,
    visible: true,
  })],
});
```

Python:

```python
import aws_cdk.aws_cloudwatch as cw

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

Java:

```java
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();
```

C# / .NET:

```csharp
using Amazon.CDK.AWS.CloudWatch;

var dashboard = new Dashboard(this, "Dash", new DashboardProps {
    DefaultInterval = Duration.Days(7),
    Variables = new [] { new DashboardVariable(new DashboardVariableOptions {
        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(new SearchComponents {
            Namespace = "AWS/Lambda",
            Dimensions = new [] { "FunctionName" },
            MetricName = "Duration",
            PopulateFrom = "FunctionName"
        }),
        DefaultValue = DefaultValue.FIRST,
        Visible = true
    }) }
});
```

Golang:

```go
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()`.

### Cross-Account Visibility

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

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

For detailed setup instructions, see [Cross-Account Cross-Region CloudWatch Console](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Cross-Account-Cross-Region.html).

To use this feature, you can set the `accountId` property on [`LogQueryWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.LogQueryWidget.html), [`GraphWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.GraphWidget.html), [`AlarmWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmWidget.html), [`SingleValueWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SingleValueWidget.html), and [`GaugeWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.GaugeWidget.html) constructs:

TypeScript:

```ts
declare const dashboard: cloudwatch.Dashboard;

dashboard.addWidgets(new cloudwatch.GraphWidget({
  // ...
  accountId: '123456789012',
}));

dashboard.addWidgets(new cloudwatch.LogQueryWidget({
  logGroupNames: ['my-log-group'],
  // ...
  accountId: '123456789012',
  queryLines: [
    'fields @message',
  ],
}));
```

Python:

```python
# dashboard: cloudwatch.Dashboard

dashboard.add_widgets(cloudwatch.GraphWidget(
    # ...
    account_id="123456789012"
))

dashboard.add_widgets(cloudwatch.LogQueryWidget(
    log_group_names=["my-log-group"],
    # ...
    account_id="123456789012",
    query_lines=["fields @message"
    ]
))
```

Java:

```java
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());
```

C# / .NET:

```csharp
Dashboard dashboard;

dashboard.AddWidgets(new GraphWidget(new GraphWidgetProps {
    // ...
    AccountId = "123456789012"
}));

dashboard.AddWidgets(new LogQueryWidget(new LogQueryWidgetProps {
    LogGroupNames = new [] { "my-log-group" },
    // ...
    AccountId = "123456789012",
    QueryLines = new [] { "fields @message" }
}));
```

Golang:

```go
var dashboard Dashboard

dashboard.AddWidgets(cloudwatch.NewGraphWidget(&GraphWidgetProps{
	// ...
	AccountId: jsii.String("123456789012"),
}))

dashboard.AddWidgets(cloudwatch.NewLogQueryWidget(&LogQueryWidgetProps{
	LogGroupNames: []*string{
		jsii.String("my-log-group"),
	},
	// ...
	AccountId: jsii.String("123456789012"),
	QueryLines: []*string{
		jsii.String("fields @message"),
	},
}))
```

## Types

### Constructs (L2)

- [`Alarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Alarm.html) Construct (L2) An alarm on a CloudWatch metric.
- [`AlarmBase`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmBase.html) Construct (L2) The base class for Alarm and CompositeAlarm resources.
- [`AlarmMuteRule`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmMuteRule.html) Construct (L2) A CloudWatch Alarm Mute Rule.
- [`AnomalyDetectionAlarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AnomalyDetectionAlarm.html) Construct (L2) CloudWatch Alarm that uses anomaly detection to trigger alarms.
- [`CompositeAlarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CompositeAlarm.html) Construct (L2) A Composite Alarm based on Alarm Rule.
- [`Dashboard`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Dashboard.html) Construct (L2) A CloudWatch dashboard.
- [`PromQLAlarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.PromQLAlarm.html) Construct (L2) A CloudWatch Alarm based on a PromQL query expression.

### Constructs (L1)

- [`CfnAccessGrant`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAccessGrant.html) Construct (L1) Resource Type definition for AWS::CloudWatch::AccessGrant.
- [`CfnAccessProfile`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAccessProfile.html) Construct (L1) Resource type definition for AWS::CloudWatch::AccessProfile.
- [`CfnAlarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.html) Construct (L1) The `AWS::CloudWatch::Alarm` type specifies an alarm and associates it with the specified metric or metric math expression.
- [`CfnAlarmMuteRule`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarmMuteRule.html) Construct (L1) Resource Type definition for AWS::CloudWatch::AlarmMuteRule that allows defining a rule and targeting alarms to mute their actions during the specified window.
- [`CfnAlert`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlert.html) Construct (L1) Resource Type definition for AWS::CloudWatch::Alert.
- [`CfnAnomalyDetector`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetector.html) Construct (L1) The `AWS::CloudWatch::AnomalyDetector` type specifies an anomaly detection band for a certain metric and statistic.
- [`CfnCompositeAlarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnCompositeAlarm.html) Construct (L1) The `AWS::CloudWatch::CompositeAlarm` type creates or updates a composite alarm.
- [`CfnDashboard`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDashboard.html) Construct (L1) The `AWS::CloudWatch::Dashboard` resource specifies an Amazon CloudWatch dashboard.
- [`CfnDomain`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomain.html) Construct (L1) Resource Type definition for AWS::CloudWatch::Domain.
- [`CfnDomainAccessGrantForOrganization`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomainAccessGrantForOrganization.html) Construct (L1) Resource Type definition for AWS::CloudWatch::DomainAccessGrantForOrganization.
- [`CfnDomainForOrganization`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomainForOrganization.html) Construct (L1) Resource Type definition for AWS::CloudWatch::DomainForOrganization.
- [`CfnInsightRule`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnInsightRule.html) Construct (L1) Creates or updates a Contributor Insights rule.
- [`CfnIntegration`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnIntegration.html) Construct (L1) Resource Type definition for AWS::CloudWatch::Integration.
- [`CfnLogAlarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnLogAlarm.html) Construct (L1) Resource Type definition for AWS::CloudWatch::LogAlarm.
- [`CfnMetricDataQueryDefinition`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnMetricDataQueryDefinition.html) Construct (L1) Resource Type definition for AWS::CloudWatch::MetricDataQueryDefinition.
- [`CfnMetricStream`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnMetricStream.html) Construct (L1) Creates or updates a metric stream.
- [`CfnOmniDashboard`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnOmniDashboard.html) Construct (L1) Resource Type definition for AWS::CloudWatch::OmniDashboard.
- [`CfnOTelEnrichment`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnOTelEnrichment.html) Construct (L1) AWS::CloudWatch::OTelEnrichment enables OTel metric enrichment in CloudWatch, allowing CloudWatch vended metrics to be available for PromQL querying enriched with AWS resource tags and metadata.
- [`CfnResourceMetricsConfiguration`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnResourceMetricsConfiguration.html) Construct (L1) Resource Type definition for AWS::CloudWatch::ResourceMetricsConfiguration.
- [`CfnSpace`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnSpace.html) Construct (L1) Resource Type definition for AWS::CloudWatch::Space.
- [`CfnView`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnView.html) Construct (L1) Resource Type definition for AWS::CloudWatch::View.

### Structs

- [`AlarmActionConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmActionConfig.html) Struct Properties for an alarm action.
- [`AlarmMuteRuleOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmMuteRuleOptions.html) Struct Options used to configure a CloudWatch alarm mute rule.
- [`AlarmMuteRuleProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmMuteRuleProps.html) Struct Properties used to configure a CloudWatch alarm mute rule.
- [`AlarmProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmProps.html) Struct Properties for Alarms.
- [`AlarmStatusWidgetProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmStatusWidgetProps.html) Struct Properties for an Alarm Status Widget.
- [`AlarmWidgetProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmWidgetProps.html) Struct Properties for an AlarmWidget.
- [`AnomalyDetectionAlarmProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AnomalyDetectionAlarmProps.html) Struct Properties for Anomaly Detection Alarms.
- [`AnomalyDetectionMetricOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AnomalyDetectionMetricOptions.html) Struct Properties needed to make an anomaly detection alarm from a metric.
- [`AtLeastOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AtLeastOptions.html) Struct Options for the AT_LEAST AlarmRule wrapper function.
- [`CalendarDateTime`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CalendarDateTime.html) Struct Represents a calendar date and time.
- [`CfnAccessGrant.AccessGrantPrincipalAttributeProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAccessGrant.AccessGrantPrincipalAttributeProperty.html) Struct A single attribute condition used to match principals for attribute-based access.
- [`CfnAccessGrant.AccessGrantPrincipalProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAccessGrant.AccessGrantPrincipalProperty.html) Struct The principal receiving the grant.
- [`CfnAccessGrant.ResourceScopeProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAccessGrant.ResourceScopeProperty.html) Struct A single resource scope entry within an access grant.
- [`CfnAccessGrant.RowScopeProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAccessGrant.RowScopeProperty.html) Struct A single additive row-level filter on an access grant.
- [`CfnAccessGrant.ScopedActionsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAccessGrant.ScopedActionsProperty.html) Struct A group of actions within an access grant, together with the resource scopes and context conditions that apply to exactly those actions.
- [`CfnAccessGrantProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAccessGrantProps.html) Struct Properties for defining a `CfnAccessGrant`.
- [`CfnAccessProfileProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAccessProfileProps.html) Struct Properties for defining a `CfnAccessProfile`.
- [`CfnAlarm.ActionConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.ActionConfigurationProperty.html) Struct
- [`CfnAlarm.AlarmPromQLCriteriaProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.AlarmPromQLCriteriaProperty.html) Struct Contains the configuration that determines how a PromQL alarm evaluates its contributors, including the query to run and the durations that define when contributors transition between states.
- [`CfnAlarm.AlarmTagsPropagationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.AlarmTagsPropagationProperty.html) Struct
- [`CfnAlarm.DimensionProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.DimensionProperty.html) Struct Dimension is an embedded property of the `AWS::CloudWatch::Alarm` type.
- [`CfnAlarm.EvaluationCriteriaProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.EvaluationCriteriaProperty.html) Struct The evaluation criteria for an alarm.
- [`CfnAlarm.EvaluationWindowProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.EvaluationWindowProperty.html) Struct The evaluation window that an alarm uses to select the range of metric data that it evaluates each time it runs.
- [`CfnAlarm.MetricDataQueryProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.MetricDataQueryProperty.html) Struct 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.
- [`CfnAlarm.MetricProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.MetricProperty.html) Struct The `Metric` property type represents a specific metric.
- [`CfnAlarm.MetricStatProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.MetricStatProperty.html) Struct This structure defines the metric to be returned, along with the statistics, period, and units.
- [`CfnAlarm.WallClockWindowProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.WallClockWindowProperty.html) Struct An evaluation window that aligns the evaluated range to fixed clock boundaries that match the alarm's period, such as the top of the hour, midnight, or the start of the calendar week, optionally in a specific time zone.
- [`CfnAlarm.WarmUpConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarm.WarmUpConfigurationProperty.html) Struct The configuration settings that define the warm-up behavior for an alarm.
- [`CfnAlarmMuteRule.MuteTargetsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarmMuteRule.MuteTargetsProperty.html) Struct Targets to be muted.
- [`CfnAlarmMuteRule.RuleProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarmMuteRule.RuleProperty.html) Struct The rule for the mute.
- [`CfnAlarmMuteRule.ScheduleProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarmMuteRule.ScheduleProperty.html) Struct Schedule for the mute to be active.
- [`CfnAlarmMuteRuleProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarmMuteRuleProps.html) Struct Properties for defining a `CfnAlarmMuteRule`.
- [`CfnAlarmProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlarmProps.html) Struct Properties for defining a `CfnAlarm`.
- [`CfnAlert.ConditionProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlert.ConditionProperty.html) Struct The thresholds that set the alert's state.
- [`CfnAlert.EvaluationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlert.EvaluationProperty.html) Struct How often the alert is evaluated, and how long a change must last before the state changes.
- [`CfnAlert.NoDataProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlert.NoDataProperty.html) Struct How the alert behaves when an evaluation returns no data.
- [`CfnAlert.NotificationRuleProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlert.NotificationRuleProperty.html) Struct A notification rule: which alert states trigger it, and where the notification is sent.
- [`CfnAlert.QueryProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlert.QueryProperty.html) Struct The query the alert runs, and the language it is written in.
- [`CfnAlert.RuleProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlert.RuleProperty.html) Struct The rule that defines how the alert is evaluated.
- [`CfnAlert.TargetProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlert.TargetProperty.html) Struct Where the notification is sent.
- [`CfnAlert.TelemetryRuleProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlert.TelemetryRuleProperty.html) Struct A rule that queries telemetry, evaluates the result against a condition, and sets how missing data is handled.
- [`CfnAlert.TriggerProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlert.TriggerProperty.html) Struct The alert states that trigger the notification rule.
- [`CfnAlertProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAlertProps.html) Struct Properties for defining a `CfnAlert`.
- [`CfnAnomalyDetector.ConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetector.ConfigurationProperty.html) Struct 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetector.DimensionProperty.html) Struct A dimension is a name/value pair that is part of the identity of a metric.
- [`CfnAnomalyDetector.MetricCharacteristicsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetector.MetricCharacteristicsProperty.html) Struct This object includes parameters that you can use to provide information to CloudWatch to help it build more accurate anomaly detection models.
- [`CfnAnomalyDetector.MetricDataQueryProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetector.MetricDataQueryProperty.html) Struct This structure is used in both `GetMetricData` and `PutMetricAlarm` .
- [`CfnAnomalyDetector.MetricMathAnomalyDetectorProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetector.MetricMathAnomalyDetectorProperty.html) Struct Indicates the CloudWatch math expression that provides the time series the anomaly detector uses as input.
- [`CfnAnomalyDetector.MetricProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetector.MetricProperty.html) Struct Represents a specific metric.
- [`CfnAnomalyDetector.MetricStatProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetector.MetricStatProperty.html) Struct This structure defines the metric to be returned, along with the statistics, period, and units.
- [`CfnAnomalyDetector.RangeProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetector.RangeProperty.html) Struct Each `Range` specifies one range of days or times to exclude from use for training or updating an anomaly detection model.
- [`CfnAnomalyDetector.SingleMetricAnomalyDetectorProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetector.SingleMetricAnomalyDetectorProperty.html) Struct Designates the CloudWatch metric and statistic that provides the time series the anomaly detector uses as input.
- [`CfnAnomalyDetectorProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnAnomalyDetectorProps.html) Struct Properties for defining a `CfnAnomalyDetector`.
- [`CfnCompositeAlarm.ActionConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnCompositeAlarm.ActionConfigurationProperty.html) Struct Configuration that applies to the notifications this alarm sends when it performs its actions.
- [`CfnCompositeAlarm.AlarmTagsPropagationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnCompositeAlarm.AlarmTagsPropagationProperty.html) Struct Controls whether the alarm's tags are included in its action notifications and state-change events, and which tag keys are included.
- [`CfnCompositeAlarmProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnCompositeAlarmProps.html) Struct Properties for defining a `CfnCompositeAlarm`.
- [`CfnDashboardProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDashboardProps.html) Struct Properties for defining a `CfnDashboard`.
- [`CfnDomain.IdentityCenterConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomain.IdentityCenterConfigurationProperty.html) Struct Identity Center configuration.
- [`CfnDomain.IdentityProviderConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomain.IdentityProviderConfigurationProperty.html) Struct Identity provider configuration for the domain.
- [`CfnDomainAccessGrantForOrganization.OrganizationAccessGrantPrincipalProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomainAccessGrantForOrganization.OrganizationAccessGrantPrincipalProperty.html) Struct The principal the grant is issued to.
- [`CfnDomainAccessGrantForOrganization.PrincipalAttributeProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomainAccessGrantForOrganization.PrincipalAttributeProperty.html) Struct An attribute key-value pair used to select principals.
- [`CfnDomainAccessGrantForOrganizationProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomainAccessGrantForOrganizationProps.html) Struct Properties for defining a `CfnDomainAccessGrantForOrganization`.
- [`CfnDomainForOrganization.IdentityCenterConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomainForOrganization.IdentityCenterConfigurationProperty.html) Struct Identity Center configuration.
- [`CfnDomainForOrganization.IdentityProviderConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomainForOrganization.IdentityProviderConfigurationProperty.html) Struct Identity provider configuration for the domain.
- [`CfnDomainForOrganizationProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomainForOrganizationProps.html) Struct Properties for defining a `CfnDomainForOrganization`.
- [`CfnDomainProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnDomainProps.html) Struct Properties for defining a `CfnDomain`.
- [`CfnInsightRuleProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnInsightRuleProps.html) Struct Properties for defining a `CfnInsightRule`.
- [`CfnIntegration.ApiKeyCredentialProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnIntegration.ApiKeyCredentialProperty.html) Struct API-key credential material that can be rotated in place on update.
- [`CfnIntegration.IntegrationCredentialProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnIntegration.IntegrationCredentialProperty.html) Struct Write-only API-key credential material for the integration.
- [`CfnIntegration.TagsItemsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnIntegration.TagsItemsProperty.html) Struct
- [`CfnIntegrationProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnIntegrationProps.html) Struct Properties for defining a `CfnIntegration`.
- [`CfnLogAlarm.ActionConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnLogAlarm.ActionConfigurationProperty.html) Struct Configuration that applies to the notifications this alarm sends when it performs its actions.
- [`CfnLogAlarm.AlarmTagsPropagationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnLogAlarm.AlarmTagsPropagationProperty.html) Struct Controls whether the alarm's tags are included in its action notifications and state-change events, and which tag keys are included.
- [`CfnLogAlarm.ScheduleConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnLogAlarm.ScheduleConfigurationProperty.html) Struct The schedule configuration for the scheduled query.
- [`CfnLogAlarm.ScheduledQueryConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnLogAlarm.ScheduledQueryConfigurationProperty.html) Struct The scheduled query configuration for the log alarm.
- [`CfnLogAlarm.WarmUpConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnLogAlarm.WarmUpConfigurationProperty.html) Struct The warm-up configuration for an alarm.
- [`CfnLogAlarmProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnLogAlarmProps.html) Struct Properties for defining a `CfnLogAlarm`.
- [`CfnMetricDataQueryDefinitionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnMetricDataQueryDefinitionProps.html) Struct Properties for defining a `CfnMetricDataQueryDefinition`.
- [`CfnMetricStream.MetricStreamFilterProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnMetricStream.MetricStreamFilterProperty.html) Struct 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnMetricStream.MetricStreamStatisticsConfigurationProperty.html) Struct This structure specifies a list of additional statistics to stream, and the metrics to stream those additional statistics for.
- [`CfnMetricStream.MetricStreamStatisticsMetricProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnMetricStream.MetricStreamStatisticsMetricProperty.html) Struct A structure that specifies the metric name and namespace for one metric that is going to have additional statistics included in the stream.
- [`CfnMetricStreamProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnMetricStreamProps.html) Struct Properties for defining a `CfnMetricStream`.
- [`CfnOmniDashboardProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnOmniDashboardProps.html) Struct Properties for defining a `CfnOmniDashboard`.
- [`CfnOTelEnrichment.OTelEnrichmentMetricSelectorProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnOTelEnrichment.OTelEnrichmentMetricSelectorProperty.html) Struct Selects metrics within one namespace.
- [`CfnOTelEnrichmentProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnOTelEnrichmentProps.html) Struct Properties for defining a `CfnOTelEnrichment`.
- [`CfnResourceMetricsConfiguration.ResourceMetricSelectionProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnResourceMetricsConfiguration.ResourceMetricSelectionProperty.html) Struct Defines which metrics are enabled for detailed monitoring on the resource.
- [`CfnResourceMetricsConfigurationProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnResourceMetricsConfigurationProps.html) Struct Properties for defining a `CfnResourceMetricsConfiguration`.
- [`CfnSpace.EncryptionConfigurationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnSpace.EncryptionConfigurationProperty.html) Struct The encryption configuration for the space.
- [`CfnSpaceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnSpaceProps.html) Struct Properties for defining a `CfnSpace`.
- [`CfnViewProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CfnViewProps.html) Struct Properties for defining a `CfnView`.
- [`CommonMetricOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CommonMetricOptions.html) Struct Options shared by most methods accepting metric options.
- [`CompositeAlarmProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CompositeAlarmProps.html) Struct Properties for creating a Composite Alarm.
- [`CreateAlarmOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CreateAlarmOptions.html) Struct Properties needed to make an alarm from a metric.
- [`CronOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CronOptions.html) Struct Options to configure a cron expression.
- [`CustomWidgetProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CustomWidgetProps.html) Struct The properties for a CustomWidget.
- [`DashboardProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.DashboardProps.html) Struct Properties for defining a CloudWatch Dashboard.
- [`DashboardVariableOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.DashboardVariableOptions.html) Struct Options for {@link DashboardVariable}.
- [`Dimension`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Dimension.html) Struct Metric dimension.
- [`GaugeWidgetProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.GaugeWidgetProps.html) Struct Properties for a GaugeWidget.
- [`GraphWidgetProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.GraphWidgetProps.html) Struct Properties for a GraphWidget.
- [`HorizontalAnnotation`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.HorizontalAnnotation.html) Struct Horizontal annotation to be added to a graph.
- [`LogQueryWidgetProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.LogQueryWidgetProps.html) Struct Properties for a Query widget.
- [`MathExpressionOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MathExpressionOptions.html) Struct Configurable options for MathExpressions.
- [`MathExpressionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MathExpressionProps.html) Struct Properties for a MathExpression.
- [`MetricConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MetricConfig.html) Struct Properties of a rendered metric.
- [`MetricExpressionConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MetricExpressionConfig.html) Struct Properties for a concrete metric.
- [`MetricOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MetricOptions.html) Struct Properties of a metric that can be changed.
- [`MetricProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MetricProps.html) Struct Properties for a metric.
- [`MetricStatConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MetricStatConfig.html) Struct Properties for a concrete metric.
- [`MetricWidgetProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MetricWidgetProps.html) Struct Basic properties for widgets that display metrics.
- [`PromQLAlarmProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.PromQLAlarmProps.html) Struct Properties for creating a PromQL Alarm.
- [`SearchComponents`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SearchComponents.html) Struct Search components for use with {@link Values.fromSearchComponents}.
- [`SearchExpressionOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SearchExpressionOptions.html) Struct Configurable options for SearchExpressions.
- [`SearchExpressionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SearchExpressionProps.html) Struct Properties for a SearchExpression.
- [`SingleValueWidgetProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SingleValueWidgetProps.html) Struct Properties for a SingleValueWidget.
- [`SpacerProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SpacerProps.html) Struct Props of the spacer.
- [`TableSummaryProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TableSummaryProps.html) Struct Properties for TableWidget's summary columns.
- [`TableWidgetProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TableWidgetProps.html) Struct Properties for a TableWidget.
- [`TextWidgetProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TextWidgetProps.html) Struct Properties for a Text widget.
- [`VariableValue`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.VariableValue.html) Struct
- [`VerticalAnnotation`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.VerticalAnnotation.html) Struct Vertical annotation to be added to a graph.
- [`YAxisProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.YAxisProps.html) Struct Properties for a Y-Axis.

### Classes

- [`AlarmRule`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmRule.html) Class Class with static functions to build AlarmRule for Composite Alarms.
- [`AlarmStatusWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmStatusWidget.html) Class A dashboard widget that displays alarms in a grid view.
- [`AlarmWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmWidget.html) Class Display the metric associated with an alarm, including the alarm line.
- [`AtLeastThreshold`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AtLeastThreshold.html) Class Threshold configuration for the AT_LEAST composite alarm rule expression.
- [`Color`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Color.html) Class A set of standard colours that can be used in annotations in a GraphWidget.
- [`Column`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Column.html) Class A widget that contains other widgets in a vertical column.
- [`ConcreteWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.ConcreteWidget.html) Class A real CloudWatch widget that has its own fixed size and remembers its position.
- [`CustomWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.CustomWidget.html) Class A CustomWidget shows the result of a AWS lambda function.
- [`DashboardVariable`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.DashboardVariable.html) Class Dashboard Variable.
- [`DefaultValue`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.DefaultValue.html) Class Default value for use in {@link DashboardVariableOptions}.
- [`GaugeWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.GaugeWidget.html) Class A dashboard gauge widget that displays metrics.
- [`GraphWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.GraphWidget.html) Class A dashboard widget that displays metrics.
- [`LogQueryWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.LogQueryWidget.html) Class Display query results from Logs Insights.
- [`MathExpression`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.MathExpression.html) Class A math expression built with metric(s) emitted by a service.
- [`Metric`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) Class A metric emitted by a service.
- [`Row`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Row.html) Class A widget that contains other widgets in a horizontal row.
- [`ScheduleExpression`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.ScheduleExpression.html) Class Schedule expression for CloudWatch alarm mute rule.
- [`SearchExpression`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SearchExpression.html) Class A CloudWatch search expression for dynamically finding and graphing multiple related metrics.
- [`SingleValueWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.SingleValueWidget.html) Class A dashboard widget that displays the most recent value for every metric.
- [`Spacer`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Spacer.html) Class A widget that doesn't display anything but takes up space.
- [`Stats`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Stats.html) Class Factory functions for standard statistics strings.
- [`TableThreshold`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TableThreshold.html) Class Thresholds for highlighting cells in TableWidget.
- [`TableWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TableWidget.html) Class A dashboard widget that displays metrics.
- [`TextWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TextWidget.html) Class A dashboard widget that displays MarkDown.
- [`Values`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Values.html) Class A class for providing values for use with {@link VariableInputType.SELECT} and {@link VariableInputType.RADIO} dashboard variables.

### Enums

- [`AlarmState`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmState.html) Enum Enumeration indicates state of Alarm used in building Alarm Rule.
- [`AlarmStatusWidgetSortBy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.AlarmStatusWidgetSortBy.html) Enum The sort possibilities for AlarmStatusWidgets.
- [`ComparisonOperator`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.ComparisonOperator.html) Enum Comparison operator for evaluating alarms.
- [`GraphWidgetView`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.GraphWidgetView.html) Enum Types of view.
- [`LegendPosition`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.LegendPosition.html) Enum The position of the legend on a GraphWidget.
- [`LogQueryLanguage`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.LogQueryLanguage.html) Enum Logs Query Language.
- [`LogQueryVisualizationType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.LogQueryVisualizationType.html) Enum Types of view.
- [`PeriodOverride`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.PeriodOverride.html) Enum Specify the period for graphs when the CloudWatch dashboard loads.
- [`Shading`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Shading.html) Enum Fill shading options that will be used with a horizontal annotation.
- [`Statistic`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Statistic.html) Enum Statistic to use over the aggregation period.
- [`TableLayout`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TableLayout.html) Enum Layout for TableWidget.
- [`TableSummaryColumn`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TableSummaryColumn.html) Enum Standard table summary columns.
- [`TextWidgetBackground`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TextWidgetBackground.html) Enum Background types available.
- [`TreatMissingData`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TreatMissingData.html) Enum Specify how missing data points are treated during alarm evaluation.
- [`Unit`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Unit.html) Enum Unit for metric.
- [`VariableInputType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.VariableInputType.html) Enum
- [`VariableType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.VariableType.html) Enum
- [`VerticalShading`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.VerticalShading.html) Enum Fill shading options that will be used with a vertical annotation.

### Interfaces

- [`IAlarm`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IAlarm.html) Interface Represents a CloudWatch Alarm.
- [`IAlarmAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IAlarmAction.html) Interface Interface for objects that can be the targets of CloudWatch alarm actions.
- [`IAlarmMuteRule`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IAlarmMuteRule.html) Interface Represents an instance of a CloudWatch alarm mute rule.
- [`IAlarmRule`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IAlarmRule.html) Interface Interface for Alarm Rule.
- [`IMetric`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IMetric.html) Interface Interface for metrics.
- [`IVariable`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IVariable.html) Interface A single dashboard variable.
- [`IWidget`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IWidget.html) Interface A single dashboard widget.
