Skip to content
v2.276.0

Alarm L2 construct ​

An alarm on a CloudWatch metric.

Example ​

ts
declare const logGroup: logs.LogGroup;
const mf = new logs.MetricFilter(this, 'MetricFilter', {
  logGroup,
  metricNamespace: 'MyApp',
  metricName: 'Latency',
  filterPattern: logs.FilterPattern.exists('$.latency'),
  metricValue: '$.latency',
  dimensions: {
    ErrorCode: '$.errorCode',
  },
  unit: cloudwatch.Unit.MILLISECONDS,
});

//expose a metric from the metric filter
const metric = mf.metric();

//you can use the metric to create a new alarm
new cloudwatch.Alarm(this, 'alarm from metric filter', {
  metric,
  threshold: 100,
  evaluationPeriods: 2,
});
python
# log_group: logs.LogGroup

mf = logs.MetricFilter(self, "MetricFilter",
    log_group=log_group,
    metric_namespace="MyApp",
    metric_name="Latency",
    filter_pattern=logs.FilterPattern.exists("$.latency"),
    metric_value="$.latency",
    dimensions={
        "ErrorCode": "$.errorCode"
    },
    unit=cloudwatch.Unit.MILLISECONDS
)

# expose a metric from the metric filter
metric = mf.metric()

# you can use the metric to create a new alarm
cloudwatch.Alarm(self, "alarm from metric filter",
    metric=metric,
    threshold=100,
    evaluation_periods=2
)
java
LogGroup logGroup;

MetricFilter mf = MetricFilter.Builder.create(this, "MetricFilter")
        .logGroup(logGroup)
        .metricNamespace("MyApp")
        .metricName("Latency")
        .filterPattern(FilterPattern.exists("$.latency"))
        .metricValue("$.latency")
        .dimensions(Map.of(
                "ErrorCode", "$.errorCode"))
        .unit(Unit.MILLISECONDS)
        .build();

//expose a metric from the metric filter
Metric metric = mf.metric();

//you can use the metric to create a new alarm
//you can use the metric to create a new alarm
Alarm.Builder.create(this, "alarm from metric filter")
        .metric(metric)
        .threshold(100)
        .evaluationPeriods(2)
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
LogGroup logGroup;

var mf = new MetricFilter(this, "MetricFilter", new MetricFilterProps {
    LogGroup = logGroup,
    MetricNamespace = "MyApp",
    MetricName = "Latency",
    FilterPattern = FilterPattern.Exists("$.latency"),
    MetricValue = "$.latency",
    Dimensions = new Dictionary<string, string> {
        { "ErrorCode", "$.errorCode" }
    },
    Unit = Unit.MILLISECONDS
});

//expose a metric from the metric filter
var metric = mf.Metric();

//you can use the metric to create a new alarm
//you can use the metric to create a new alarm
new Alarm(this, "alarm from metric filter", new AlarmProps {
    Metric = metric,
    Threshold = 100,
    EvaluationPeriods = 2
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var logGroup LogGroup

mf := logs.NewMetricFilter(this, jsii.String("MetricFilter"), &MetricFilterProps{
	LogGroup: LogGroup,
	MetricNamespace: jsii.String("MyApp"),
	MetricName: jsii.String("Latency"),
	FilterPattern: logs.FilterPattern_Exists(jsii.String("$.latency")),
	MetricValue: jsii.String("$.latency"),
	Dimensions: map[string]*string{
		"ErrorCode": jsii.String("$.errorCode"),
	},
	Unit: cloudwatch.Unit_MILLISECONDS,
})

//expose a metric from the metric filter
metric := mf.Metric()

//you can use the metric to create a new alarm
//you can use the metric to create a new alarm
cloudwatch.NewAlarm(this, jsii.String("alarm from metric filter"), &AlarmProps{
	Metric: Metric,
	Threshold: jsii.Number(100),
	EvaluationPeriods: jsii.Number(2),
})

Initializer ​

ts
new Alarm(scope: Construct, id: string, props: AlarmProps)
python
Alarm(scope: Construct, id: str, props: AlarmProps)
java
new Alarm(Construct scope, String id, AlarmProps props)
csharp
new Alarm(Construct scope, string id, AlarmProps props)
go
NewAlarm(Scope Construct, Id *string, Props AlarmProps)

Construct Props ​

actionsEnabledoptionalbooleanactions_enabledoptionalboolactionsEnabledoptionalBooleanActionsEnabledoptionalboolActionsEnabledoptional*bool= true#
Whether the actions for this alarm are enabled.
alarmDescriptionoptionalstringalarm_descriptionoptionalstralarmDescriptionoptionalStringAlarmDescriptionoptionalstringAlarmDescriptionoptional*string#
Description for the alarm.

Default: No description

alarmNameoptionalstringalarm_nameoptionalstralarmNameoptionalStringAlarmNameoptionalstringAlarmNameoptional*string#
Name of the alarm.

Default: Automatically generated name

comparisonOperatoroptionalComparisonOperatorcomparison_operatoroptionalComparisonOperatorcomparisonOperatoroptionalComparisonOperatorComparisonOperatoroptionalComparisonOperatorComparisonOperatoroptionalComparisonOperator= GreaterThanOrEqualToThreshold#
Comparison to use to check if metric is breaching.
datapointsToAlarmoptionalnumberdatapoints_to_alarmoptionalint | floatdatapointsToAlarmoptionalNumberDatapointsToAlarmoptionaldoubleDatapointsToAlarmoptional*float64= ``evaluationPeriods``#
The number of datapoints that must be breaching to trigger the alarm.

This is used only if you are setting an "M out of N" alarm. In that case, this value is the M. For more information, see Evaluating an Alarm in the Amazon CloudWatch User Guide.

evaluateLowSampleCountPercentileoptionalstringevaluate_low_sample_count_percentileoptionalstrevaluateLowSampleCountPercentileoptionalStringEvaluateLowSampleCountPercentileoptionalstringEvaluateLowSampleCountPercentileoptional*string#
Specifies whether to evaluate the data and potentially change the alarm state if there are too few data points to be statistically significant.

Default: Not configured.

Used only for alarms that are based on percentiles.

evaluationPeriodsnumberevaluation_periodsint | floatevaluationPeriodsNumberEvaluationPeriodsdoubleEvaluationPeriods*float64required#
The number of periods over which data is compared to the specified threshold.
metricIMetricmetricIMetricmetricIMetricMetricIMetricMetricIMetricrequired#
The metric to add the alarm on.

Metric objects can be obtained from most resources, or you can construct custom Metric objects by instantiating one.

thresholdnumberthresholdint | floatthresholdNumberThresholddoubleThreshold*float64required#
The value against which the specified statistic is compared.
treatMissingDataoptionalTreatMissingDatatreat_missing_dataoptionalTreatMissingDatatreatMissingDataoptionalTreatMissingDataTreatMissingDataoptionalTreatMissingDataTreatMissingDataoptionalTreatMissingData= TreatMissingData.Missing#
Sets how this alarm is to handle missing data points.

Properties ​

alarmArnstringalarm_arnstralarmArnStringAlarmArnstringAlarmArn*string#
ARN of this alarm.
alarmNamestringalarm_namestralarmNameStringAlarmNamestringAlarmName*string#
Name of this alarm.
A reference to a Alarm resource.
ANOMALY_DETECTION_NO_THRESHOLDnumberanomaly_detection_no_thresholdint | floatANOMALY_DETECTION_NO_THRESHOLDNumberANOMALY_DETECTION_NO_THRESHOLDdoubleANOMALY_DETECTION_NO_THRESHOLD*float64static#
Conventional value for the threshold property when creating anomaly detection alarms.
notes

Anomaly detection alarms don't have numbered threshold. Instead, they have a dynamically calculated threshold based on the metric math expression that contains a metric expression.

The threshold property is required, but the value is ignored. This constant has the value 0, and has a symbolic name to indicate why the threshold is 0. You can use new AnomalyDetectionAlarm() to avoid having to pass the threshold property at all.

The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

metricIMetricmetricIMetricmetricIMetricMetricIMetricMetricIMetric#
The metric object this alarm was based on.
nodeNodenodeNodenodeNodeNodeNodeNodeNode#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringstatic#
Uniquely identifies this class.
stackStackstackStackstackStackStackStackStackStack#
The stack in which this resource is defined.

Methods ​

addAlarmAction(...actions: IAlarmAction[]): voiddef add_alarm_action(self, actions: IAlarmAction) -> Nonepublic void addAlarmAction(IAlarmAction actions)public void AddAlarmAction(IAlarmAction actions)func AddAlarmAction(Actions IAlarmAction)#
Trigger this action if the alarm fires.

Typically SnsAction or AutoScalingAction.

addAlarmMuteRule(id: string, options: AlarmMuteRuleOptions): AlarmMuteRuledef add_alarm_mute_rule(self, id: str, options: AlarmMuteRuleOptions) -> AlarmMuteRulepublic AlarmMuteRule addAlarmMuteRule(String id, AlarmMuteRuleOptions options)public AlarmMuteRule AddAlarmMuteRule(string id, AlarmMuteRuleOptions options)func AddAlarmMuteRule(Id *string, Options AlarmMuteRuleOptions) AlarmMuteRule#
Add an alarm mute rule.
addInsufficientDataAction(...actions: IAlarmAction[]): voiddef add_insufficient_data_action(self, actions: IAlarmAction) -> Nonepublic void addInsufficientDataAction(IAlarmAction actions)public void AddInsufficientDataAction(IAlarmAction actions)func AddInsufficientDataAction(Actions IAlarmAction)#
Trigger this action if there is insufficient data to evaluate the alarm.

Typically SnsAction or AutoScalingAction.

addOkAction(...actions: IAlarmAction[]): voiddef add_ok_action(self, actions: IAlarmAction) -> Nonepublic void addOkAction(IAlarmAction actions)public void AddOkAction(IAlarmAction actions)func AddOkAction(Actions IAlarmAction)#
Trigger this action if the alarm returns from breaching state into ok state.

Typically SnsAction or AutoScalingAction.

applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

fromAlarmArn(scope: Construct, id: string, alarmArn: string): IAlarm@staticmethod def from_alarm_arn(scope: Construct, id: str, alarm_arn: str) -> IAlarmpublic static IAlarm fromAlarmArn(Construct scope, String id, String alarmArn)public static IAlarm FromAlarmArn(Construct scope, string id, string alarmArn)func FromAlarmArn(Scope Construct, Id *string, AlarmArn *string) IAlarmstatic#
Import an existing CloudWatch alarm provided an ARN.
3 parameters

Parameters

  • scopescopescopescopeScope — The parent creating construct (usually this).
  • ididididId — The construct's name.
  • alarmArnalarm_arnalarmArnalarmArnAlarmArn — Alarm ARN (i.e. arn:aws:cloudwatch:<region>:<account-id>:alarm:Foo).
fromAlarmName(scope: Construct, id: string, alarmName: string): IAlarm@staticmethod def from_alarm_name(scope: Construct, id: str, alarm_name: str) -> IAlarmpublic static IAlarm fromAlarmName(Construct scope, String id, String alarmName)public static IAlarm FromAlarmName(Construct scope, string id, string alarmName)func FromAlarmName(Scope Construct, Id *string, AlarmName *string) IAlarmstatic#
Import an existing CloudWatch alarm provided an Name.
3 parameters

Parameters

  • scopescopescopescopeScope — The parent creating construct (usually this).
  • ididididId — The construct's name.
  • alarmNamealarm_namealarmNamealarmNameAlarmName — Alarm Name.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
renderAlarmRule(): stringdef render_alarm_rule(self, ) -> strpublic String renderAlarmRule()public string RenderAlarmRule()func RenderAlarmRule() *string#
AlarmRule indicating ALARM state for Alarm.
toAnnotation(): HorizontalAnnotationdef to_annotation(self, ) -> HorizontalAnnotationpublic HorizontalAnnotation toAnnotation()public HorizontalAnnotation ToAnnotation()func ToAnnotation() HorizontalAnnotation#
Turn this alarm into a horizontal annotation.
notes

This is useful if you want to represent an Alarm in a non-AlarmWidget. An AlarmWidget can directly show an alarm, but it can only show a single alarm and no other metrics. Instead, you can convert the alarm to a HorizontalAnnotation and add it as an annotation to another graph.

This might be useful if:

  • You want to show multiple alarms inside a single graph, for example if you have both a "small margin/long period" alarm as well as a "large margin/short period" alarm.

  • You want to show an Alarm line in a graph with multiple metrics in it.

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.