# Amazon CloudWatch Construct Library
<!--BEGIN STABILITY BANNER-->---
![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)
![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)
---
<!--END STABILITY BANNER-->
## 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:
```python
# fn: lambda.Function
errors = fn.metric_errors()
```
`Metric` objects can be account and region aware. You can specify `account` and `region` as properties of the metric, or use the `metric.attachTo(Construct)` method. `metric.attachTo()` will automatically copy the `region` and `account` fields of the `Construct`, which can come from anywhere in the Construct tree.
You can also instantiate `Metric` objects to reference any
[published metric](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:
```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
}
)
```
### Instantiating a new Metric object
If you want to reference a metric that is not yet exposed by an existing construct,
you can instantiate a `Metric` object to represent it. For example:
```python
metric = cloudwatch.Metric(
namespace="MyNamespace",
metric_name="MyMetric",
dimensions_map={
"ProcessingStep": "Download"
}
)
```
### Metric Math
Math expressions are supported by instantiating the `MathExpression` class.
For example, a math expression that sums two other metrics looks like this:
```python
# fn: lambda.Function
all_problems = cloudwatch.MathExpression(
expression="errors + throttles",
using_metrics={
"errors": fn.metric_errors(),
"faults": fn.metric_throttles()
}
)
```
You can use `MathExpression` objects like any other metric, including using
them in other math expressions:
```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()
}
)
```
### Search Expressions
Math expressions also support search expressions. For example, the following
search expression returns all CPUUtilization metrics that it finds, with the
graph showing the Average statistic with an aggregation period of 5 minutes:
```python
cpu_utilization = cloudwatch.MathExpression(
expression="SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 300)",
# Specifying '' as the label suppresses the default behavior
# of using the expression as metric label. This is especially appropriate
# when using expressions that return multiple time series (like SEARCH()
# or METRICS()), to show the labels of the retrieved metrics only.
label=""
)
```
Cross-account and cross-region search expressions are also supported. Use
the `searchAccount` and `searchRegion` properties to specify the account
and/or region to evaluate the search expression against.
### Aggregation
To graph or alarm on metrics you must aggregate them first, using a function
like `Average` or a percentile function like `P99`. By default, most Metric objects
returned by CDK libraries will be configured as `Average` over `300 seconds` (5 minutes).
The exception is if the metric represents a count of discrete events, such as
failures. In that case, the Metric object will be configured as `Sum` over `300 seconds`, i.e. it represents the number of times that event occurred over the
time period.
If you want to change the default aggregation of the Metric object (for example,
the function or the period), you can do so by passing additional parameters
to the metric function call:
```python
# fn: lambda.Function
minute_error_rate = fn.metric_errors(
statistic="avg",
period=Duration.minutes(1),
label="Lambda failure rate"
)
```
This function also allows changing the metric label or color (which will be
useful when embedding them in graphs, see below).
> Rates versus Sums
>
> The reason for using `Sum` to count discrete events is that *some* events are
> emitted as either `0` or `1` (for example `Errors` for a Lambda) and some are
> only emitted as `1` (for example `NumberOfMessagesPublished` for an SNS
> topic).
>
> In case `0`-metrics are emitted, it makes sense to take the `Average` of this
> metric: the result will be the fraction of errors over all executions.
>
> If `0`-metrics are not emitted, the `Average` will always be equal to `1`,
> and not be very useful.
>
> In order to simplify the mental model of `Metric` objects, we default to
> aggregating using `Sum`, which will be the same for both metrics types. If you
> happen to know the Metric you want to alarm on makes sense as a rate
> (`Average`) you can always choose to change the statistic.
### Labels
Metric labels are displayed in the legend of graphs that include the metrics.
You can use [dynamic labels](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:
```python
# fn: lambda.Function
minute_error_rate = fn.metric_errors(
statistic="sum",
period=Duration.hours(1),
# Show the maximum hourly error count in the legend
label="[max: ${MAX}] Lambda failure rate"
)
```
As the metric label, the maximum value in the visible range will
be shown next to the time series name in the graph's legend.
If the metric is a math expression producing more than one time series, the
maximum will be individually calculated and shown for each time series produce
by the math expression.
## Alarms
Alarms can be created on metrics in one of two ways. Either create an `Alarm`
object, passing the `Metric` object to set the alarm on:
```python
# fn: lambda.Function
cloudwatch.Alarm(self, "Alarm",
metric=fn.metric_errors(),
threshold=100,
evaluation_periods=2
)
```
Alternatively, you can call `metric.createAlarm()`:
```python
# fn: lambda.Function
fn.metric_errors().create_alarm(self, "Alarm",
threshold=100,
evaluation_periods=2
)
```
The most important properties to set while creating an Alarms are:
* `threshold`: the value to compare the metric against.
* `comparisonOperator`: the comparison operation to use, defaults to `metric >= threshold`.
* `evaluationPeriods`: how many consecutive periods the metric has to be
breaching the the threshold for the alarm to trigger.
To create a cross-account alarm, make sure you have 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` object either manually or via the `metric.attachTo()` method.
### Alarm Actions
To add actions to an alarm, use the integration classes from the
`@aws-cdk/aws-cloudwatch-actions` package. For example, to post a message to
an SNS topic when an alarm breaches, do the following:
```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))
```
#### 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.
```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))),
cloudwatch.AlarmRule.from_boolean(False))
cloudwatch.CompositeAlarm(self, "MyAwesomeCompositeAlarm",
alarm_rule=alarm_rule
)
```
### A note on units
In CloudWatch, Metrics datums are emitted with units, such as `seconds` or
`bytes`. When `Metric` objects are given a `unit` attribute, it will be used to
*filter* the stream of metric datums for datums emitted using the same `unit`
attribute.
In particular, the `unit` field is *not* used to rescale datums or alarm threshold
values (for example, it cannot be used to specify an alarm threshold in
*Megabytes* if the metric stream is being emitted as *bytes*).
You almost certainly don't want to specify the `unit` property when creating
`Metric` objects (which will retrieve all datums regardless of their unit),
unless you have very specific requirements. Note that in any case, CloudWatch
only supports filtering by `unit` for Alarms, not in Dashboard graphs.
Please see the following GitHub issue for a discussion on real unit
calculations in CDK: https://github.com/aws/aws-cdk/issues/5595
## Dashboards
Dashboards are set of Widgets stored server-side which can be accessed quickly
from the AWS console. Available widgets are graphs of a metric over time, the
current value of a metric, or a static piece of Markdown which explains what the
graphs mean.
The following widgets are available:
* `GraphWidget` -- shows any number of metrics on both the left and right
vertical axes.
* `AlarmWidget` -- shows the graph and alarm line for a single alarm.
* `SingleValueWidget` -- shows the current value of a set of metrics.
* `TextWidget` -- shows some static Markdown.
* `AlarmStatusWidget` -- shows the status of your alarms in a grid view.
### Graph widget
A graph widget can display any number of metrics on either the `left` or
`right` vertical axis:
```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="average",
label="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 the right y-axis.
```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")
]
))
```
The graph legend can be adjusted from the default position at bottom of the widget.
```python
# dashboard: cloudwatch.Dashboard
dashboard.add_widgets(cloudwatch.GraphWidget(
# ...
legend_position=cloudwatch.LegendPosition.RIGHT
))
```
The graph can publish live data within the last minute that has not been fully aggregated.
```python
# dashboard: cloudwatch.Dashboard
dashboard.add_widgets(cloudwatch.GraphWidget(
# ...
live_data=True
))
```
The graph view can be changed from default 'timeSeries' to 'bar' or 'pie'.
```python
# dashboard: cloudwatch.Dashboard
dashboard.add_widgets(cloudwatch.GraphWidget(
# ...
view=cloudwatch.GraphWidgetView.BAR
))
```
### Alarm widget
An alarm widget shows the graph and the alarm line of a single alarm:
```python
# dashboard: cloudwatch.Dashboard
# error_alarm: cloudwatch.Alarm
dashboard.add_widgets(cloudwatch.AlarmWidget(
title="Errors",
alarm=error_alarm
))
```
### 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):
```python
# dashboard: cloudwatch.Dashboard
# visitor_count: cloudwatch.Metric
# purchase_count: cloudwatch.Metric
dashboard.add_widgets(cloudwatch.SingleValueWidget(
metrics=[visitor_count, purchase_count]
))
```
Show as many digits as can fit, before rounding.
```python
# dashboard: cloudwatch.Dashboard
dashboard.add_widgets(cloudwatch.SingleValueWidget(
metrics=[],
full_precision=True
))
```
### Text widget
A text widget shows an arbitrary piece of MarkDown. Use this to add explanations
to your dashboard:
```python
# dashboard: cloudwatch.Dashboard
dashboard.add_widgets(cloudwatch.TextWidget(
markdown="# Key Performance Indicators"
))
```
### Alarm Status widget
An alarm status widget displays instantly the status of any type of alarms and gives the
ability to aggregate one or more alarms together in a small surface.
```python
# dashboard: cloudwatch.Dashboard
# error_alarm: cloudwatch.Alarm
dashboard.add_widgets(
cloudwatch.AlarmStatusWidget(
alarms=[error_alarm]
))
```
An alarm status widget only showing firing alarms, sorted by state and timestamp:
```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]
))
```
### Query results widget
A `LogQueryWidget` shows the results of a query from Logs Insights:
```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/"
]
))
```
### Custom widget
A `CustomWidget` shows the result of an AWS Lambda function:
```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"
))
```
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`: stack two or more widgets vertically.
* `Row`: lay out two or more widgets horizontally.
* `Spacer`: take up empty space
Raw data
{
"_id": null,
"home_page": "https://github.com/aws/aws-cdk",
"name": "aws-cdk.aws-cloudwatch",
"maintainer": "",
"docs_url": null,
"requires_python": "~=3.7",
"maintainer_email": "",
"keywords": "",
"author": "Amazon Web Services",
"author_email": "",
"download_url": "https://files.pythonhosted.org/packages/d2/37/9592cc771fcdc4352338984db4a2febc69edfa0e8a8d540e69a855c87508/aws-cdk.aws-cloudwatch-1.203.0.tar.gz",
"platform": null,
"description": "# Amazon CloudWatch Construct Library\n\n<!--BEGIN STABILITY BANNER-->---\n\n\n![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)\n\n![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)\n\n---\n<!--END STABILITY BANNER-->\n\n## Metric objects\n\nMetric objects represent a metric that is emitted by AWS services or your own\napplication, such as `CPUUsage`, `FailureCount` or `Bandwidth`.\n\nMetric objects can be constructed directly or are exposed by resources as\nattributes. Resources that expose metrics will have functions that look\nlike `metricXxx()` which will return a Metric object, initialized with defaults\nthat make sense.\n\nFor example, `lambda.Function` objects have the `fn.metricErrors()` method, which\nrepresents the amount of errors reported by that Lambda function:\n\n```python\n# fn: lambda.Function\n\n\nerrors = fn.metric_errors()\n```\n\n`Metric` objects can be account and region aware. You can specify `account` and `region` as properties of the metric, or use the `metric.attachTo(Construct)` method. `metric.attachTo()` will automatically copy the `region` and `account` fields of the `Construct`, which can come from anywhere in the Construct tree.\n\nYou can also instantiate `Metric` objects to reference any\n[published metric](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-services-cloudwatch-metrics.html)\nthat's not exposed using a convenience method on the CDK construct.\nFor example:\n\n```python\nhosted_zone = route53.HostedZone(self, \"MyHostedZone\", zone_name=\"example.org\")\nmetric = cloudwatch.Metric(\n namespace=\"AWS/Route53\",\n metric_name=\"DNSQueries\",\n dimensions_map={\n \"HostedZoneId\": hosted_zone.hosted_zone_id\n }\n)\n```\n\n### Instantiating a new Metric object\n\nIf you want to reference a metric that is not yet exposed by an existing construct,\nyou can instantiate a `Metric` object to represent it. For example:\n\n```python\nmetric = cloudwatch.Metric(\n namespace=\"MyNamespace\",\n metric_name=\"MyMetric\",\n dimensions_map={\n \"ProcessingStep\": \"Download\"\n }\n)\n```\n\n### Metric Math\n\nMath expressions are supported by instantiating the `MathExpression` class.\nFor example, a math expression that sums two other metrics looks like this:\n\n```python\n# fn: lambda.Function\n\n\nall_problems = cloudwatch.MathExpression(\n expression=\"errors + throttles\",\n using_metrics={\n \"errors\": fn.metric_errors(),\n \"faults\": fn.metric_throttles()\n }\n)\n```\n\nYou can use `MathExpression` objects like any other metric, including using\nthem in other math expressions:\n\n```python\n# fn: lambda.Function\n# all_problems: cloudwatch.MathExpression\n\n\nproblem_percentage = cloudwatch.MathExpression(\n expression=\"(problems / invocations) * 100\",\n using_metrics={\n \"problems\": all_problems,\n \"invocations\": fn.metric_invocations()\n }\n)\n```\n\n### Search Expressions\n\nMath expressions also support search expressions. For example, the following\nsearch expression returns all CPUUtilization metrics that it finds, with the\ngraph showing the Average statistic with an aggregation period of 5 minutes:\n\n```python\ncpu_utilization = cloudwatch.MathExpression(\n expression=\"SEARCH('{AWS/EC2,InstanceId} MetricName=\\\"CPUUtilization\\\"', 'Average', 300)\",\n\n # Specifying '' as the label suppresses the default behavior\n # of using the expression as metric label. This is especially appropriate\n # when using expressions that return multiple time series (like SEARCH()\n # or METRICS()), to show the labels of the retrieved metrics only.\n label=\"\"\n)\n```\n\nCross-account and cross-region search expressions are also supported. Use\nthe `searchAccount` and `searchRegion` properties to specify the account\nand/or region to evaluate the search expression against.\n\n### Aggregation\n\nTo graph or alarm on metrics you must aggregate them first, using a function\nlike `Average` or a percentile function like `P99`. By default, most Metric objects\nreturned by CDK libraries will be configured as `Average` over `300 seconds` (5 minutes).\nThe exception is if the metric represents a count of discrete events, such as\nfailures. 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\ntime period.\n\nIf you want to change the default aggregation of the Metric object (for example,\nthe function or the period), you can do so by passing additional parameters\nto the metric function call:\n\n```python\n# fn: lambda.Function\n\n\nminute_error_rate = fn.metric_errors(\n statistic=\"avg\",\n period=Duration.minutes(1),\n label=\"Lambda failure rate\"\n)\n```\n\nThis function also allows changing the metric label or color (which will be\nuseful when embedding them in graphs, see below).\n\n> Rates versus Sums\n>\n> The reason for using `Sum` to count discrete events is that *some* events are\n> emitted as either `0` or `1` (for example `Errors` for a Lambda) and some are\n> only emitted as `1` (for example `NumberOfMessagesPublished` for an SNS\n> topic).\n>\n> In case `0`-metrics are emitted, it makes sense to take the `Average` of this\n> metric: the result will be the fraction of errors over all executions.\n>\n> If `0`-metrics are not emitted, the `Average` will always be equal to `1`,\n> and not be very useful.\n>\n> In order to simplify the mental model of `Metric` objects, we default to\n> aggregating using `Sum`, which will be the same for both metrics types. If you\n> happen to know the Metric you want to alarm on makes sense as a rate\n> (`Average`) you can always choose to change the statistic.\n\n### Labels\n\nMetric labels are displayed in the legend of graphs that include the metrics.\n\nYou can use [dynamic labels](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/graph-dynamic-labels.html)\nto show summary information about the displayed time series\nin the legend. For example, if you use:\n\n```python\n# fn: lambda.Function\n\n\nminute_error_rate = fn.metric_errors(\n statistic=\"sum\",\n period=Duration.hours(1),\n\n # Show the maximum hourly error count in the legend\n label=\"[max: ${MAX}] Lambda failure rate\"\n)\n```\n\nAs the metric label, the maximum value in the visible range will\nbe shown next to the time series name in the graph's legend.\n\nIf the metric is a math expression producing more than one time series, the\nmaximum will be individually calculated and shown for each time series produce\nby the math expression.\n\n## Alarms\n\nAlarms can be created on metrics in one of two ways. Either create an `Alarm`\nobject, passing the `Metric` object to set the alarm on:\n\n```python\n# fn: lambda.Function\n\n\ncloudwatch.Alarm(self, \"Alarm\",\n metric=fn.metric_errors(),\n threshold=100,\n evaluation_periods=2\n)\n```\n\nAlternatively, you can call `metric.createAlarm()`:\n\n```python\n# fn: lambda.Function\n\n\nfn.metric_errors().create_alarm(self, \"Alarm\",\n threshold=100,\n evaluation_periods=2\n)\n```\n\nThe most important properties to set while creating an Alarms are:\n\n* `threshold`: the value to compare the metric against.\n* `comparisonOperator`: the comparison operation to use, defaults to `metric >= threshold`.\n* `evaluationPeriods`: how many consecutive periods the metric has to be\n breaching the the threshold for the alarm to trigger.\n\nTo 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` object either manually or via the `metric.attachTo()` method.\n\n### Alarm Actions\n\nTo add actions to an alarm, use the integration classes from the\n`@aws-cdk/aws-cloudwatch-actions` package. For example, to post a message to\nan SNS topic when an alarm breaches, do the following:\n\n```python\nimport aws_cdk.aws_cloudwatch_actions as cw_actions\n# alarm: cloudwatch.Alarm\n\n\ntopic = sns.Topic(self, \"Topic\")\nalarm.add_alarm_action(cw_actions.SnsAction(topic))\n```\n\n#### Notification formats\n\nAlarms can be created in one of two \"formats\":\n\n* With \"top-level parameters\" (these are the classic style of CloudWatch Alarms).\n* With a list of metrics specifications (these are the modern style of CloudWatch Alarms).\n\nFor backwards compatibility, CDK will try to create classic, top-level CloudWatch alarms\nas much as possible, unless you are using features that cannot be expressed in that format.\nFeatures that require the new-style alarm format are:\n\n* Metric math\n* Cross-account metrics\n* Labels\n\nThe difference between these two does not impact the functionality of the alarm\nin any way, *except* that the format of the notifications the Alarm generates is\ndifferent between them. This affects both the notifications sent out over SNS,\nas well as the EventBridge events generated by this Alarm. If you are writing\ncode to consume these notifications, be sure to handle both formats.\n\n### Composite Alarms\n\n[Composite Alarms](https://aws.amazon.com/about-aws/whats-new/2020/03/amazon-cloudwatch-now-allows-you-to-combine-multiple-alarms/)\ncan be created from existing Alarm resources.\n\n```python\n# alarm1: cloudwatch.Alarm\n# alarm2: cloudwatch.Alarm\n# alarm3: cloudwatch.Alarm\n# alarm4: cloudwatch.Alarm\n\n\nalarm_rule = cloudwatch.AlarmRule.any_of(\n cloudwatch.AlarmRule.all_of(\n cloudwatch.AlarmRule.any_of(alarm1,\n cloudwatch.AlarmRule.from_alarm(alarm2, cloudwatch.AlarmState.OK), alarm3),\n cloudwatch.AlarmRule.not(cloudwatch.AlarmRule.from_alarm(alarm4, cloudwatch.AlarmState.INSUFFICIENT_DATA))),\n cloudwatch.AlarmRule.from_boolean(False))\n\ncloudwatch.CompositeAlarm(self, \"MyAwesomeCompositeAlarm\",\n alarm_rule=alarm_rule\n)\n```\n\n### A note on units\n\nIn CloudWatch, Metrics datums are emitted with units, such as `seconds` or\n`bytes`. When `Metric` objects are given a `unit` attribute, it will be used to\n*filter* the stream of metric datums for datums emitted using the same `unit`\nattribute.\n\nIn particular, the `unit` field is *not* used to rescale datums or alarm threshold\nvalues (for example, it cannot be used to specify an alarm threshold in\n*Megabytes* if the metric stream is being emitted as *bytes*).\n\nYou almost certainly don't want to specify the `unit` property when creating\n`Metric` objects (which will retrieve all datums regardless of their unit),\nunless you have very specific requirements. Note that in any case, CloudWatch\nonly supports filtering by `unit` for Alarms, not in Dashboard graphs.\n\nPlease see the following GitHub issue for a discussion on real unit\ncalculations in CDK: https://github.com/aws/aws-cdk/issues/5595\n\n## Dashboards\n\nDashboards are set of Widgets stored server-side which can be accessed quickly\nfrom the AWS console. Available widgets are graphs of a metric over time, the\ncurrent value of a metric, or a static piece of Markdown which explains what the\ngraphs mean.\n\nThe following widgets are available:\n\n* `GraphWidget` -- shows any number of metrics on both the left and right\n vertical axes.\n* `AlarmWidget` -- shows the graph and alarm line for a single alarm.\n* `SingleValueWidget` -- shows the current value of a set of metrics.\n* `TextWidget` -- shows some static Markdown.\n* `AlarmStatusWidget` -- shows the status of your alarms in a grid view.\n\n### Graph widget\n\nA graph widget can display any number of metrics on either the `left` or\n`right` vertical axis:\n\n```python\n# dashboard: cloudwatch.Dashboard\n# execution_count_metric: cloudwatch.Metric\n# error_count_metric: cloudwatch.Metric\n\n\ndashboard.add_widgets(cloudwatch.GraphWidget(\n title=\"Executions vs error rate\",\n\n left=[execution_count_metric],\n\n right=[error_count_metric.with(\n statistic=\"average\",\n label=\"Error rate\",\n color=cloudwatch.Color.GREEN\n )]\n))\n```\n\nUsing the methods `addLeftMetric()` and `addRightMetric()` you can add metrics to a graph widget later on.\n\nGraph widgets can also display annotations attached to the left or the right y-axis.\n\n```python\n# dashboard: cloudwatch.Dashboard\n\n\ndashboard.add_widgets(cloudwatch.GraphWidget(\n # ...\n\n 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\")\n ]\n))\n```\n\nThe graph legend can be adjusted from the default position at bottom of the widget.\n\n```python\n# dashboard: cloudwatch.Dashboard\n\n\ndashboard.add_widgets(cloudwatch.GraphWidget(\n # ...\n\n legend_position=cloudwatch.LegendPosition.RIGHT\n))\n```\n\nThe graph can publish live data within the last minute that has not been fully aggregated.\n\n```python\n# dashboard: cloudwatch.Dashboard\n\n\ndashboard.add_widgets(cloudwatch.GraphWidget(\n # ...\n\n live_data=True\n))\n```\n\nThe graph view can be changed from default 'timeSeries' to 'bar' or 'pie'.\n\n```python\n# dashboard: cloudwatch.Dashboard\n\n\ndashboard.add_widgets(cloudwatch.GraphWidget(\n # ...\n\n view=cloudwatch.GraphWidgetView.BAR\n))\n```\n\n### Alarm widget\n\nAn alarm widget shows the graph and the alarm line of a single alarm:\n\n```python\n# dashboard: cloudwatch.Dashboard\n# error_alarm: cloudwatch.Alarm\n\n\ndashboard.add_widgets(cloudwatch.AlarmWidget(\n title=\"Errors\",\n alarm=error_alarm\n))\n```\n\n### Single value widget\n\nA single-value widget shows the latest value of a set of metrics (as opposed\nto a graph of the value over time):\n\n```python\n# dashboard: cloudwatch.Dashboard\n# visitor_count: cloudwatch.Metric\n# purchase_count: cloudwatch.Metric\n\n\ndashboard.add_widgets(cloudwatch.SingleValueWidget(\n metrics=[visitor_count, purchase_count]\n))\n```\n\nShow as many digits as can fit, before rounding.\n\n```python\n# dashboard: cloudwatch.Dashboard\n\n\ndashboard.add_widgets(cloudwatch.SingleValueWidget(\n metrics=[],\n\n full_precision=True\n))\n```\n\n### Text widget\n\nA text widget shows an arbitrary piece of MarkDown. Use this to add explanations\nto your dashboard:\n\n```python\n# dashboard: cloudwatch.Dashboard\n\n\ndashboard.add_widgets(cloudwatch.TextWidget(\n markdown=\"# Key Performance Indicators\"\n))\n```\n\n### Alarm Status widget\n\nAn alarm status widget displays instantly the status of any type of alarms and gives the\nability to aggregate one or more alarms together in a small surface.\n\n```python\n# dashboard: cloudwatch.Dashboard\n# error_alarm: cloudwatch.Alarm\n\n\ndashboard.add_widgets(\n cloudwatch.AlarmStatusWidget(\n alarms=[error_alarm]\n ))\n```\n\nAn alarm status widget only showing firing alarms, sorted by state and timestamp:\n\n```python\n# dashboard: cloudwatch.Dashboard\n# error_alarm: cloudwatch.Alarm\n\n\ndashboard.add_widgets(cloudwatch.AlarmStatusWidget(\n title=\"Errors\",\n alarms=[error_alarm],\n sort_by=cloudwatch.AlarmStatusWidgetSortBy.STATE_UPDATED_TIMESTAMP,\n states=[cloudwatch.AlarmState.ALARM]\n))\n```\n\n### Query results widget\n\nA `LogQueryWidget` shows the results of a query from Logs Insights:\n\n```python\n# dashboard: cloudwatch.Dashboard\n\n\ndashboard.add_widgets(cloudwatch.LogQueryWidget(\n log_group_names=[\"my-log-group\"],\n view=cloudwatch.LogQueryVisualizationType.TABLE,\n # The lines will be automatically combined using '\\n|'.\n query_lines=[\"fields @message\", \"filter @message like /Error/\"\n ]\n))\n```\n\n### Custom widget\n\nA `CustomWidget` shows the result of an AWS Lambda function:\n\n```python\n# dashboard: cloudwatch.Dashboard\n\n\n# Import or create a lambda function\nfn = lambda_.Function.from_function_arn(dashboard, \"Function\", \"arn:aws:lambda:us-east-1:123456789012:function:MyFn\")\n\ndashboard.add_widgets(cloudwatch.CustomWidget(\n function_arn=fn.function_arn,\n title=\"My lambda baked widget\"\n))\n```\n\nYou 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).\n\n### Dashboard Layout\n\nThe widgets on a dashboard are visually laid out in a grid that is 24 columns\nwide. Normally you specify X and Y coordinates for the widgets on a Dashboard,\nbut because this is inconvenient to do manually, the library contains a simple\nlayout system to help you lay out your dashboards the way you want them to.\n\nWidgets have a `width` and `height` property, and they will be automatically\nlaid out either horizontally or vertically stacked to fill out the available\nspace.\n\nWidgets are added to a Dashboard by calling `add(widget1, widget2, ...)`.\nWidgets given in the same call will be laid out horizontally. Widgets given\nin different calls will be laid out vertically. To make more complex layouts,\nyou can use the following widgets to pack widgets together in different ways:\n\n* `Column`: stack two or more widgets vertically.\n* `Row`: lay out two or more widgets horizontally.\n* `Spacer`: take up empty space\n\n\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "The CDK Construct Library for AWS::CloudWatch",
"version": "1.203.0",
"project_urls": {
"Homepage": "https://github.com/aws/aws-cdk",
"Source": "https://github.com/aws/aws-cdk.git"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "7e712390e710f192ceff38771eff8208be5462c61e12c8bce23e812667dc997d",
"md5": "c1d49bacfe35b1ed5191314657394058",
"sha256": "738ec541e729830df31b7a132054f595f592c257fa5a9f7624b0f012a183759f"
},
"downloads": -1,
"filename": "aws_cdk.aws_cloudwatch-1.203.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "c1d49bacfe35b1ed5191314657394058",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "~=3.7",
"size": 395856,
"upload_time": "2023-05-31T22:53:29",
"upload_time_iso_8601": "2023-05-31T22:53:29.150050Z",
"url": "https://files.pythonhosted.org/packages/7e/71/2390e710f192ceff38771eff8208be5462c61e12c8bce23e812667dc997d/aws_cdk.aws_cloudwatch-1.203.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "d2379592cc771fcdc4352338984db4a2febc69edfa0e8a8d540e69a855c87508",
"md5": "4c5558204f00ddd03faed58d0de207b6",
"sha256": "5bac09367efce7a82a2d91e6172462a1696f6468472a77c0573daf216a4c8d44"
},
"downloads": -1,
"filename": "aws-cdk.aws-cloudwatch-1.203.0.tar.gz",
"has_sig": false,
"md5_digest": "4c5558204f00ddd03faed58d0de207b6",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "~=3.7",
"size": 397074,
"upload_time": "2023-05-31T23:01:16",
"upload_time_iso_8601": "2023-05-31T23:01:16.912096Z",
"url": "https://files.pythonhosted.org/packages/d2/37/9592cc771fcdc4352338984db4a2febc69edfa0e8a8d540e69a855c87508/aws-cdk.aws-cloudwatch-1.203.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-05-31 23:01:16",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "aws",
"github_project": "aws-cdk",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "aws-cdk.aws-cloudwatch"
}