0

我是 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)
4

1 回答 1

1

这些行:

        STAT = 100
        write_metric(STAT, metric)

始终100作为您的价值发送。

于 2018-10-12T00:48:46.010 回答