AWS Lambda在CloudWatch指标中写入了错误的输出

时间:2018-10-11 23:31:40

标签: amazon-web-services aws-lambda amazon-cloudwatch amazon-cloudwatchlogs amazon-cloudwatch-metrics

我是Devops和编码的新手。我正在使用CloudWatch和Lambda构建监视工具(grafana)。

我的代码无法正常工作。 ping服务器。如果返回200,它将在指标中推0,而当网站关闭时,它应该推1,但是当我在写指标中提到写1时,而不是写1时写100,并且如果我尝试执行任何操作其他值则表示其发布数大于100,但小于刚发布的100数小于100。

这是代码:

import boto3

import urllib2

def write_metric(value, metric):

    d = boto3.client('cloudwatch')
    d.put_metric_data(Namespace='WebsiteStatus',
                      MetricData=[
                          {
                      'MetricName':metric,
                      'Dimensions':[
                          {
                      'Name': 'Status',
                      'Value': 'WebsiteStatusCode',
                          },
                          ],
                      'Value': value,
    },
    ]
                      )

def check_site(url, metric):

    STAT = 1
    print("Checking %s " % url)
    request = urllib2.Request("https://" +url)

    try:
        response = urllib2.urlopen(request)
        response.close()
    except urllib2.URLError as e:
        if hasattr(e, 'code'):
            print ("[Error:] Connection to %s failed with code: " %url +str(e.code))
            STAT = 100
            write_metric(STAT, metric)
        if hasattr(e, 'reason'):
            print ("[Error:] Connection to %s failed with code: " % url +str(e.reason))
            STAT = 100
            write_metric(STAT, metric)
    except urllib2.HTTPError as e:
        if hasattr(e, 'code'):
            print ("[Error:] Connection to %s failed with code: " % url + str(e.code))
            STAT = 100
            write_metric(STAT, metric)
        if hasattr(e, 'reason'):
            print ("[Error:] Connection to %s failed with code: " % url + str(e.reason))
            STAT = 100
            write_metric(STAT, metric)
        print('HTTPError!!!')

    if STAT != 100:
        STAT = response.getcode()

    return STAT

def lambda_handler(event, context):


    websiteurls = [
        "website.com"
    ]
    metricname = 'SiteAvailability'

    for site in websiteurls:
        r = check_site(site,metricname)
        if r == 200:
            print("Site %s is up" %site)
            write_metric(0, metricname)
        else:
            print("[Error:] Site %s down" %site)
            write_metric(1, metricname)

1 个答案:

答案 0 :(得分:1)

这些行:

        STAT = 100
        write_metric(STAT, metric)

始终发送100作为您的值。