Invoking the Lambda Function with a CloudWatch Logs event. Every log that is created or matches the filter pattern will automatically invoke the Lambda Function and log the received event. If you want multiple log groups for a single subscription, you can create multiple SubscriptionFilter
instances with different log groups but the same Lambda function as the destination. If you want to create a Lambda Subscription Filter via Console or AWS CLI, you can comment out the CloudWatch-related CDK code in the stack file and follow the steps below.
Grant CloudWatch Logs permission to execute the Lambda Function. Use the following command and replace the placeholder account_id
with your account, and the placeholder region
with your desired region.
aws lambda add-permission \
--function-name "handleSubscription" \
--statement-id "handleSubscription" \
--principal "logs.amazonaws.com" \
--action "lambda:InvokeFunction" \
--source-arn "arn:aws:logs:region:account_id:log-group:*:*" \
--source-account "account_id"
- Go to CloudWatch → Logs → Log groups → Log Group Name
- Go to Subscription filters → Create → Create Lambda subscription filter
- Choose the Lambda function for the destination that you want to subscribe to the filter
- Configure log format and filters
Here's a sample lambda subscription filter:
-
Create a subscription filter using the following command and replace the placeholder
account_id
with your account, the placeholderregion
with your desired region, the placeholderlog_group_name
with the log group to process, and the placeholderfilter_pattern
with your desired pattern.aws logs put-subscription-filter \ --log-group-name "log_group_name" \ --filter-name "log_error_subscription" \ --filter-pattern "filter_pattern" \ --destination-arn "arn:aws:lambda:region:account_id:function:handleSubscription"
- What is Amazon CloudWatch?
- What Is Amazon CloudWatch Events?
- Using Lambda with CloudWatch Logs
- Using CloudWatch Logs subscription filters
- Using Subscription Filters in Amazon CloudWatch Logs
- Creating a role to delegate permissions to an AWS service
npm run build
compile typescript to jsnpm run watch
watch for changes and compilenpm run test
perform the jest unit testscdk deploy
deploy this stack to your default AWS account/regioncdk diff
compare deployed stack with current statecdk synth
emits the synthesized CloudFormation template
-
Install all the dependencies, bootstrap your project, and synthesized CloudFormation template.
# Without passing "profile" parameter dev@dev:~:aws-cdk-samples/cloudwatch/cloudwatch-subscription-lambda$ make init # With "profile" parameter dev@dev:~:aws-cdk-samples/cloudwatch/cloudwatch-subscription-lambda$ make init profile=[profile_name]
-
Deploy the project.
# Without passing "profile" parameter dev@dev:~:aws-cdk-samples/cloudwatch/cloudwatch-subscription-lambda$ make deploy # With "profile" parameter dev@dev:~:aws-cdk-samples/cloudwatch/cloudwatch-subscription-lambda$ make deploy profile=[profile_name]