AWS CloudWatch is helpful for storing and retrieving logs for various AWS resources. It tells us what is really happening with our infrastructure in the form of logs, metrics, alarms, and dashboards. Sometimes, there is a need to perform some action if something occurs within a resource e.g. an error or warning log. For this kind of work, we can use a native feature of AWS CloudWatch called Subscription Filter.

What is a Subscription Filter?

Subscription filters allow you to define rules for forwarding log events from AWS CloudWatch log groups to different AWS services such as Amazon Kinesis, AWS Lambda, or an Amazon OpenSearch service. This feature is useful for processing and analyzing log data in real time or for triggering specific actions based on log events.

Types of Subscription Filters

AWS supports different AWS services as subscription filters, which are as follows:

You can use any of the above services as your filter, depending on your use case e.g, data processing, storage, notifications etc. However, please note that you can use up to two filters for a single log group.

Use Case

For our use case, we will be using the AWS Lambda function as a destination for the subscription filter. AWS CloudWatch log group will forward the log events, matching a specific pattern and trigger the lambda function accordingly.

approach

import gzip
import base64
def lambda_handler(event, context):
    encoded_zipped_data = event['awslogs']['data']
    zipped_data = base64.b64decode(encoded_zipped_data)
    data = gzip.decompress(zipped_data)

In the above code snippet, the decoded data is stored in the data variable. Now, you can parse it and get the desired response data and perform your custom operations accordingly.

Conclusion

By using AWS CloudWatch Subscription filters, you can automate the processes within your AWS ecosystem based on log events and can monitor changes more closely. This will automate the error log checking more efficiently and will perform error log checks for you.

Leave a Reply

Your email address will not be published. Required fields are marked *