未使用boto3

时间:2016-06-01 01:00:56

标签: python amazon-web-services lambda metrics cloudwatch

我试图编写AWS Lambda,它将遍历所有Cloudwatch日志组,为每个日志组的搜索词创建一个度量标准过滤器。

不幸的是我发现尽管我对put_metric_filter的所有调用都收到HTTP 200响应,但大多数调用都没有创建任何内容(4/15调用导致创建过滤器)。

我有一个带有此处理程序文件的AWS Lambda' 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)

其中调用了来自' basicExample.py'的ManageMetricsAndAlarms类。它映射在一组日志组名称上,为每个日志组名称创建一个度量标准,用于过滤术语' 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

  # -------------------------------------------------

我对python很陌生,所以我希望我错过了一些基本的东西,但是我们非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

要考虑的几件事:

  1. 为什么要把它放在lambda上?您要每分钟/小时将相同的过滤器放在相同的lambda上吗?通常,您只应执行一次脚本(或在部署新的lambda之后立即执行。)

  2. map是一个懒惰的求值者,因此您需要类似
    的东西 list(map(function x: print(x), iterable)) 如果要执行功能

这是一个例子

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))