1

I just start learning on aws, and I have created couple of cloudwatch log custom metric filter and subscribe to the same lambda function do to some stuff, but I want to get my lambda function to perform difference action depends on which metric filter trigger it. In the lambda function(in python) how can I know which metric filter trigger it?

hobbyking
  • 97
  • 10

1 Answers1

0

In Lambda function handlers, you'll have an event object, this object will usually contain information about the request. According to the documentation, this is base64 encoded and zipped. I imagine this is because the logs are expected to get fairly large.

Once unzipped the structure is:

{ messageType: 'DATA_MESSAGE',
  owner: '123456789123',
  logGroup: 'testLogGroup',
  logStream: 'testLogStream',
  subscriptionFilters: [ 'testFilter' ],
  logEvents: 
   [ { id: 'eventId1',
       timestamp: 1440442987000,
       message: '[ERROR] First test message' },
     { id: 'eventId2',
       timestamp: 1440442987001,
       message: '[ERROR] Second test message' } ] }

This can be found in the AWS docs under CloudWatch Logs.

You can check on the subscriptionFilters field in the event data to check which filter triggered the Lambda.

If your Lambda was in NodeJS, you could write something like the following:

const zlib = require('zlib');
const YOUR_FILTER = 'filter1';

exports.handler = async (event) => {
    const zippedInput = new Buffer(event.awslogs.data, 'base64');
    await new Promise((resolve, reject) => {
        zlib.gunzip(zippedInput, function (e, buffer) {
            const awslogsData = JSON.parse(buffer.toString('utf-8'));
            // Conditions on filters to do something
            if (awslogsData.subscriptionFilters.includes(YOUR_FILTER)) {
                // do something
            } else if (awslogsData.subscriptionFilters.includes('your_other_filter')) {
                // do something else
            }

            resolve();
        });
    })

    return 'Hello from Lambda!'
};
  • I need to do it in python, and I saw some example on the net to decode and unzip the log data the following is part of my function: `def lambda_handler(event, context): outEvent = str(event['awslogs']['data']) outEvent = gzip.GzipFile(fileobj=StringIO(outEvent.decode('base64','strict'))).read()` But it return the following error: `'str' object has no attribute 'decode': AttributeError : outEvent = gzip.GzipFile(fileobj=StringIO(outEvent.decode('base64','strict'))).read() AttributeError: 'str' object has no attribute 'decode'` How to resolve this error? – hobbyking May 18 '18 at 05:17
  • String.decode was removed in python3, you should import base64 and do something like `base64.b64decode(outEvent)` instead. – Aaron Williams May 18 '18 at 06:18