0

I have below output after tabulating response from cloudwatch using get_metric_statistics. I would like to add validation that if any Sum is greater than 0 it will print a message saying there is an error. And if all Sum is equal to zero it will say no error.

> +| Timestamp              |   Sum | Unit   | |
> 2021-01-12T09:31:00+00:00 |     0 | Count  | |
> 2021-01-12T09:30:00+00:00 |     0 | Count  | |
> 2021-01-12T09:33:00+00:00 |     0 | Count  | |
> 2021-01-12T09:29:00+00:00 |     0 | Count  | |
> 2021-01-12T09:32:00+00:00 |     0 | Count  | |
> 2021-01-12T09:28:00+00:00 |     0 | Count  |
> +---------------------------+-------+--------+

Below is my python script

import json
import boto3
import os
from datetime import datetime, timedelta
from tabulate import tabulate

client = boto3.client("lambda")


class DateTimeEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()

        return json.JSONEncoder.default(self, o)


client = boto3.client("cloudwatch")
response = client.get_metric_statistics(
    Namespace="AWS/Lambda",
    MetricName="Errors",
    Dimensions=[{"Name": "FunctionName", "Value": "XXX"}],
    StartTime=datetime.utcnow() - timedelta(seconds=360),
    EndTime=datetime.utcnow(),
    Period=60,
    Statistics=["Sum"],
)

message = json.dumps(response, cls=DateTimeEncoder)
message2 = json.loads(message)
message3 = message2["Datapoints"]
message4 = tabulate(message3, headers="keys", tablefmt="psql")
print(message4)

I know this seems easy but please help. Thanks!

MJG
  • 23
  • 1
  • 1
  • 6

1 Answers1

1

add something like:

for message in message2:
   if message["Sum"] > 0:
      print("Some error occured")
   else:
      pass

so if you don't get a feedback, there's no error. In case some Sum is greater 0, it'll tell you Some error

grumpyp
  • 432
  • 4
  • 10
  • Thanks @grumpyp but I am having this error when adding your code. Traceback (most recent call last): File ".\geterrorV5.py", line 36, in if message["Sum"] > 0: TypeError: string indices must be integers – MJG Jan 14 '21 at 00:15
  • It worked when changing it to for message2 in message3: if message2["Sum"] > 0: print("Some error occured") else: pass – MJG Jan 14 '21 at 00:23
  • Is there a way to just print one line message? Like if any has sum greater than 0 it will print some error occurred? Because with the above code it prints multiple lines that Some error occurred depending on number of sum that is greater than 0. – MJG Jan 14 '21 at 00:35
  • Sure thats possible. You could add `error = True` after the `if message["Sum"] > 0:` statement. Then you could check this variable by `if error is True: print("Some error occured")` – grumpyp Jan 14 '21 at 08:09