I'm attempting to write an AWS Lambda which will loop over all Cloudwatch log groups, creating a metric filter for a search term on each log group.
Unfortunately I am finding that although all of my calls to put_metric_filter receive HTTP 200 responses, most of the calls result in nothing getting created (4/15 calls resulting in the creation of a filter).
I have an AWS Lambda with this handler file 'handler.py':
from __future__ import print_function
from basicExample import ManageMetricsAndAlarms
import json, logging
log = logging.getLogger()
log.setLevel(logging.INFO)
def handler(event, context):
log.info("Received event {}".format(json.dumps(event)))
mc = ManageMetricsAndAlarms(event, context)
response = mc.main()
return json.dumps(response)
Which calls the ManageMetricsAndAlarms class from 'basicExample.py' which maps over an array of log group names, creating a metric for each which filters on the term 'ERROR':
from __future__ import print_function
import boto3, os, sys, json, botocore, logging
log = logging.getLogger()
log.setLevel(logging.INFO)
class ManageMetricsAndAlarms:
# -------------------------------------------------
def __init__(self,event,context):
self.event = event
# -------------------------------------------------
def main(self):
cloudwatch = boto3.resource('cloudwatch')
metricsNamespace = 'ExampleMetrics'
errorFilter = '{ $.levelname = "ERROR" }'
# Supposing that I have log groups for 10 imaginatively named lambdas
logGroupNames = [
'/aws/lambda/Lambda-1', '/aws/lambda/Lambda-2',
'/aws/lambda/Lambda-3', '/aws/lambda/Lambda-4',
'/aws/lambda/Lambda-5', '/aws/lambda/Lambda-6',
'/aws/lambda/Lambda-7', '/aws/lambda/Lambda-8',
'/aws/lambda/Lambda-9', '/aws/lambda/Lambda-10'
]
# map over the log groups adding a metric filter for 'ERROR' to each
responses = map(lambda lg: self.createErrorFilter(metricsNamespace, errorFilter, lg), logGroupNames)
return responses
# -------------------------------------------------
def createErrorFilter(self, metricsNamespace, filterPattern, logGroup):
metricName = logGroup + '_ErrorCount'
logs_client = boto3.client('logs')
log.info('Put metric filter ' + metricName + ' with filter $.levelname-ERROR on logGroup: ' + logGroup)
errorFilter = logs_client.put_metric_filter(
logGroupName = logGroup,
filterName ='ERROR-filter',
filterPattern = filterPattern,
metricTransformations = [
{
'metricNamespace': metricsNamespace,
'metricValue': '1',
'metricName': metricName,
}
]
)
log.info('errorFilter response: ' + json.dumps(errorFilter))
return errorFilter
# -------------------------------------------------
I'm quite new to python so I expect I've missed something basic but any help would be much appreciated!