0

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!

jamesw
  • 63
  • 1
  • 11
  • Have you found a solution? I have the same problem – drpexe Oct 14 '16 at 20:10
  • Not sure if the anwser apply to your case, but I found out that timestamp in CloudWatch logs is in microseconds, not seconds. SO multiplying it by 1000 worked. – drpexe Oct 14 '16 at 20:25

1 Answers1

1

Few things to consider:

  1. Why would you put this on a lambda? are you going to put the same filter every minute/hour on the same lambdas? In general you should execute your script only once (or just after deploying new lambdas.

  2. map is a lazy evaluator, so you will need something like
    list(map(function x: print(x), iterable)) if you want to execute the function

Here is an example

import boto3


def createErrorFilter(metricsNamespace, filterPattern, logGroup):


    metricName = logGroup + '_example'
    logs_client = boto3.client('logs')

    errorFilter = logs_client.put_metric_filter(
    logGroupName = logGroup,
    filterName ='ERROR-filter',
    filterPattern = filterPattern,
    metricTransformations = [
        {
            'metricNamespace': metricsNamespace,
            'metricValue': '1',
            'metricName': metricName,
        }
    ]
    )
    print('ok')
    return 

cloudwatch = boto3.resource('cloudwatch')
metricsNamespace = 'ExampleMetrics-2'
errorFilter = 'ERROR'


logGroupNames = [
  '/aws/lambda/lambda1', '/aws/lambda/lambda2'
]

# map over the log groups adding a metric filter for 'ERROR' to each
responses = list(map(lambda lg: createErrorFilter(metricsNamespace, errorFilter, lg), logGroupNames))

DaveR
  • 1,696
  • 18
  • 24