- Notifications
You must be signed in to change notification settings - Fork0
A Serverless Framework plugin that creates CloudWatch alarms for functions.
License
finn-auto/serverless-plugin-aws-alerts
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A Serverless plugin to easily add CloudWatch alarms to functions
npm i serverless-plugin-aws-alerts --save-devORyarn add --dev serverless-plugin-aws-alerts
# serverless.ymlplugins: -serverless-plugin-aws-alertscustom:alerts:stages: -productiontopics:alarm:topic:${self:service}-${opt:stage}-alerts-alarmnotifications: -protocol:emailendpoint:name@domain.com# Change this to your email addressalarms: -functionErrors -functionThrottles
service:your-serviceprovider:name:awsruntime:nodejs12.xplugins: -serverless-plugin-aws-alertscustom:alerts:stages:# Optionally - select which stages to deploy alarms to -production -stagingdashboards:truenameTemplate:$[functionName]-$[metricName]-Alarm# Optionally - naming template for alarms, can be overwritten in definitionsprefixTemplate:$[stackName]# Optionally - override the alarm name prefixtopics:ok:${self:service}-${opt:stage}-alerts-okalarm:${self:service}-${opt:stage}-alerts-alarminsufficientData:${self:service}-${opt:stage}-alerts-insufficientDatadefinitions:# these defaults are merged with your definitionsfunctionErrors:period:300# override periodcustomAlarm:actionsEnabled:false# Indicates whether actions should be executed during any changes to the alarm state. The default is TRUEdescription:'My custom alarm'namespace:'AWS/Lambda'nameTemplate:$[functionName]-Duration-IMPORTANT-Alarm# Optionally - naming template for the alarms, overwrites globally defined oneprefixTemplate:$[stackName]# Optionally - override the alarm name prefix, overwrites globally defined onemetric:durationthreshold:200statistic:Averageperiod:300evaluationPeriods:1datapointsToAlarm:1comparisonOperator:GreaterThanOrEqualToThresholdalarms: -functionThrottles -functionErrors -functionInvocations -functionDurationfunctions:foo:handler:foo.handleralarms:# merged with function alarms -customAlarm -name:fooAlarm# creates new alarm or overwrites some properties of the alarm (with the same name) from definitionsnamespace:'AWS/Lambda'actionsEnabled:falsemetric:errors# define custom metrics herethreshold:1statistic:Minimumperiod:60evaluationPeriods:1datapointsToAlarm:1comparisonOperator:GreaterThanOrEqualToThreshold
You can create alarms usingCloudWatch AnomalyDetection to alarm when data is outside a number of standard deviations of normal, rather than at a static threshold.When using anomaly detection alarms the threshold property specifies the "Anomaly Detection Threshold" seen in the AWS console.
Default alarms can also be updated to be anomaly detection alarms by adding thetype: anomalyDetection
property.
functions:foo:handler:foo.handleralarms: -name:fooAlarmtype:anomalyDetectionnamespace:'AWS/Lambda'metric:Invocationsthreshold:2statistic:Sumperiod:60evaluationPeriods:1datapointsToAlarm:1comparisonOperator:LessThanLowerOrGreaterThanUpperThresholdbar:handler:bar.handleralarms: -name:functionErrorsthreshold:2type:anomalyDetectioncomparisonOperator:LessThanLowerOrGreaterThanUpperThreshold -name:functionInvocationsthreshold:2type:anomalyDetectioncomparisonOperator:LessThanLowerOrGreaterThanUpperThreshold
You can define several topics for alarms. For example you want to have topics for critical alarmsreaching your pagerduty, and different topics for noncritical alarms, which just send you emails.
In each alarm definition you have to specify which topics you want to use. In following exampleyou get an email for each function error, pagerduty gets alarm only if there are more than 20errors in 60s
custom:alerts:topics:critical:ok:topic:${self:service}-${opt:stage}-critical-alerts-oknotifications: -protocol:httpsendpoint:https://events.pagerduty.com/integration/.../enqueuealarm:topic:${self:service}-${opt:stage}-critical-alerts-alarmnotifications: -protocol:httpsendpoint:https://events.pagerduty.com/integration/.../enqueuenonCritical:alarm:topic:${self:service}-${opt:stage}-nonCritical-alerts-alarmnotifications: -protocol:emailendpoint:alarms@email.comdefinitions:# these defaults are merged with your definitionscriticalFunctionErrors:namespace:'AWS/Lambda'metric:Errorsthreshold:20statistic:Sumperiod:60evaluationPeriods:10comparisonOperator:GreaterThanOrEqualToThresholdokActions: -criticalalarmActions: -criticalnonCriticalFunctionErrors:namespace:'AWS/Lambda'metric:Errorsthreshold:1statistic:Sumperiod:60evaluationPeriods:10comparisonOperator:GreaterThanOrEqualToThresholdalarmActions: -nonCriticalalarms: -criticalFunctionErrors -nonCriticalFunctionErrors
If topic name is specified, plugin assumes that topic does not exist and will create it. To use existing topics, specify ARNs or use CloudFormation (e.g. Fn::ImportValue, Fn::Join and Ref) to refer to existing topics.
custom:alerts:topics:alarm:topic:arn:aws:sns:${self:region}:${self::accountId}:monitoring-${opt:stage}
custom:alerts:topics:alarm:topic:Fn::ImportValue:ServiceMonitoring:monitoring-${opt:stage, 'dev'}ok:topic:Fn::Join: -':' -- arn:aws:sns -Ref:AWS::Region -Ref:AWS::AccountId -example-ok-topicinsufficientData:topic:Ref:ExampleInsufficientdataTopicresources:Resources:ExampleInsufficientdataTopic:Type:AWS::SNS::TopicProperties:DisplayName:example-insufficientdata-topicSubscription: -Endpoint:me@example.comProtocol:EMAIL
You can configure subscriptions to your SNS topics within yourserverless.yml
. For each subscription, you'll need to specify aprotocol
and anendpoint
.
The following example will send email notifications tome@example.com
for all messages to the Alarm topic:
custom:alerts:topics:alarm:topic:${self:service}-${opt:stage}-alerts-alarmnotifications: -protocol:emailendpoint:me@example.com
You can configure notifications to send to webhook URLs, to SMS devices, to other Lambda functions, and more. Check out the AWS docshere for configuration options.
You can monitor a log group for a function for a specific pattern. Do this by adding the pattern key.You can learn about custom patterns at:http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html
The following would create a custom metric log filter based alarm namedbarExceptions
. Any function that included this alarm would have its logs scanned for the patternexception Bar
and if found would trigger an alarm.
custom:alerts:definitions:barExceptions:metric:barExceptionsthreshold:0statistic:Minimumperiod:60evaluationPeriods:1comparisonOperator:GreaterThanThresholdpattern:'exception Bar'bunyanErrors:metric:bunyanErrorsthreshold:0statistic:Sumperiod:60evaluationPeriods:1datapointsToAlarm:1comparisonOperator:GreaterThanThresholdpattern:'{$.level > 40}'
Note: For custom log metrics, namespace property will automatically be set to stack name (e.g.
fooservice-dev
).
You can define custom naming template for the alarms.nameTemplate
property underalerts
configures naming template for all the alarms, while placingnameTemplate
under alarm definition configures (overwrites) it for that specific alarm only. Naming template provides interpolation capabilities, where supported placeholders are:
$[functionName]
- function name (e.g.helloWorld
)$[functionId]
- function logical id (e.g.HelloWorldLambdaFunction
)$[metricName]
- metric name (e.g.Duration
)$[metricId]
- metric id (e.g.BunyanErrorsHelloWorldLambdaFunction
for the log based alarms,$[metricName]
otherwise)
Note: All the alarm names are prefixed with stack name (e.g.
fooservice-dev
).
The plugin provides some default definitions that you can simply drop into your application. For example:
alerts:alarms: -functionErrors -functionThrottles -functionInvocations -functionDuration
If these definitions do not quite suit i.e. the threshold is too high, you can override a setting withoutcreating a completely new definition.
alerts:definitions:# these defaults are merged with your definitionsfunctionErrors:period:300# override periodtreatMissingData:notBreaching# override treatMissingData
The default definitions are below.
definitions:functionInvocations:namespace:'AWS/Lambda'metric:Invocationsthreshold:100statistic:Sumperiod:60evaluationPeriods:1datapointsToAlarm:1comparisonOperator:GreaterThanOrEqualToThresholdtreatMissingData:missingfunctionErrors:namespace:'AWS/Lambda'metric:Errorsthreshold:1statistic:Sumperiod:60evaluationPeriods:1datapointsToAlarm:1comparisonOperator:GreaterThanOrEqualToThresholdtreatMissingData:missingfunctionDuration:namespace:'AWS/Lambda'metric:Durationthreshold:500statistic:Averageperiod:60evaluationPeriods:1comparisonOperator:GreaterThanOrEqualToThresholdtreatMissingData:missingfunctionThrottles:namespace:'AWS/Lambda'metric:Throttlesthreshold:1statistic:Sumperiod:60evaluationPeriods:1datapointsToAlarm:1comparisonOperator:GreaterThanOrEqualToThresholdtreatMissingData:missing
Default alarms can be disabled on a per-function basis:
custom:alerts:alarms: -functionThrottles -functionErrors -functionInvocations -functionDurationfunctions:bar:handler:bar.handleralarms: -name:functionInvocationsenabled:false
The plugin allows users to provide custom dimensions for the alarm. Dimensions are provided in a list of key/value pairs {Name: foo, Value:bar}The plugin will always apply dimension of {Name: FunctionName, Value: ((FunctionName))}, except if the parameteromitDefaultDimension: true
is passed. For example:
alarms:# merged with function alarms -name:fooAlarmnamespace:'AWS/Lambda'metric:errors# define custom metrics herethreshold:1statistic:Minimumperiod:60evaluationPeriods:1comparisonOperator:GreaterThanThresholdomitDefaultDimension:truedimensions: -Name:fooValue:bar
'Dimensions': [ {'Name': 'foo','Value': 'bar' },]
Statistic not only supports SampleCount, Average, Sum, Minimum or Maximum as defined in CloudFormationhere, but also percentiles. This is possible by leveragingExtendedStatistic under the hood. This plugin will automatically choose the correct key for you. See an example below:
definitions:functionDuration:namespace:'AWS/Lambda'metric:Durationthreshold:100statistic:'p95'period:60evaluationPeriods:1datapointsToAlarm:1comparisonOperator:GreaterThanThresholdtreatMissingData:missingevaluateLowSampleCountPercentile:ignore
If your Serverless CloudFormation stack is growing too large and you're running out of resources,you can configure the plugin to deploy a separate stack for the CloudWatch resources. The defaultbehaviour is to create a stack with a "-alerts" suffix in the stack name.
custom: alerts: externalStack: true
You can customize the name suffix:
custom: alerts: externalStack: nameSuffix: Alerts
The separate stack will be automatically deployed after you've deployed your main Serverlessstack. It will also be automatically removed if you remove your main stack.
You can also enable the external stack on the command line withsls deploy --alerts-external-stack
which is equivalent to addingexternalStack: true
to the configuration.
The plugin can create dashboards automatically for basic metrics.
Default setup for a single dashboard:
dashboards:true
Create a vertical dashboard:
dashboards:vertical
Create dashboards only in specified stages:
dashboards:stages: -production -stagingtemplates: -default
MIT ©A Cloud Guru
About
A Serverless Framework plugin that creates CloudWatch alarms for functions.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Languages
- JavaScript99.9%
- Shell0.1%