Create custom metric

CloudWatch metric provides several metrics for Lambda functions such as the number of times the function is executed, the execution time of each time, error rates, and throttle count. To see the metrics of a certain function we do the following steps.

  1. Open AWS Lambda console.

    • Click Functions on the left menu.
    • Choose the books_list function. CloudWatchMetrics
  2. At books_list page.

    • Click the Monitor tab.
    • You can see the CloudWatch metrics are displayed. CloudWatchMetrics
  3. Next, we will create a new custom metric that sums up the number of hits to DynamoDB that fail. At books_list page.

    • Click the Code tab.

    • Copy the following code.

      import json
      import os
      import boto3
      from decimal import *
      from boto3.dynamodb.types import TypeDeserializer
      
      client = boto3.client('dynamodb') 
      # 1. BỔ SUNG: Khởi tạo thêm CloudWatch client
      cloudwatch = boto3.client('cloudwatch')
      
      serializer = TypeDeserializer()
      
      table_name = os.environ['TABLE_NAME']
      
      class DecimalEncoder(json.JSONEncoder):
          def default(self, obj):
              if isinstance(obj, Decimal):
                  return str(obj)
              return json.JSONEncoder.default(self, obj)
      
      def deserialize(data):
          if isinstance(data, list):
              return [deserialize(v) for v in data]
      
          if isinstance(data, dict):
              try:
                  return serializer.deserialize(data)
              except TypeError:
                  return {k: deserialize(v) for k, v in data.items()}
          else:
              return data
      
      def lambda_handler(event, context):
          # 2. BỔ SUNG: Bao bọc bằng try...
          try:
              data_books = client.scan(
                  TableName='Book',
                  IndexName='name-index'
              )
      
              format_data_books = deserialize(data_books["Items"])
              for book in format_data_books:
                  data_comment = client.query(
                      TableName=table_name, 
                      KeyConditionExpression="id = :id AND rv_id > :rv_id", 
                      ExpressionAttributeValues={
                          ":id": {"S": book['id']}, 
                          ":rv_id": {"N": "0"}
                      }
                  )
                  format_data_comment = deserialize(data_comment['Items'])
                  print(data_comment['Items'])
                  book["comments"] = format_data_comment
      
              print (format_data_books)
              return {
                  "statusCode": 200,
                  "headers": {
                      "Content-Type": "application/json",
                      "Access-Control-Allow-Origin": "*",
                      "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE, OPTIONS",
                      "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Access-Token,XKey,Authorization"
                  },
                  "body": json.dumps(format_data_books, cls=DecimalEncoder)
              }
      
          # 3. BỔ SUNG: Khối except đẩy Metric lên Cloudwatch nếu lỗi
          except Exception as e:
              print(f'Error getting items: {e}')
      
              cloudwatch.put_metric_data(
                  Namespace='BooksList_Lambda',
                  MetricData=[
                      {
                          'MetricName': 'FailedConnectToDynamoDB',
                          'Dimensions': [
                              {
                                  'Name': 'env',
                                  'Value': 'staging'
                              },
                          ],
                          'Value': 1.0,
                          'Unit': 'Seconds'
                      },
                  ]
              )
      
              raise Exception(f'Error getting items: {e}')
      
    • Click the Deploy button. CloudWatchMetrics

  4. At books_list page.

    • Click the Configuration tab.
    • Click the Permissions on the left menu.
    • Click the fcaj-book-store-BooksListRole-… at Role name. CloudWatchMetrics
  5. At fcaj-book-store-BooksListRole-… page.

    • Click the Permissions tab.
    • Click the + at BooksListRolePolicy0 Policy name.
    • Click the Edit button. CloudWatchMetrics
  6. At Step 1: Modify permissions in BooksListRolePolicy0 page.

    • Click the JSON tab.

    • Copy the following code to the Policy editor.

      {
          "Sid": "VisualEditor0",
          "Effect": "Allow",
          "Action": "cloudwatch:PutMetricData",
          "Resource": "*"
      },
      

      CloudWatchMetrics

    • Scroll down to the bottom and click the Next button. CloudWatchMetrics

  7. At Step 2: Review and save page.

    • Click the Save changes button. CloudWatchMetrics
    • You will see a success message that the policy is updated. CloudWatchMetrics
  8. Open Postman to recall the api, the error returned is Internal server error. CloudWatchMetrics

  9. Back to books_list Lambda function page.

    • Click the Monitor tab.
    • Click the View CloudWatch logs button. CloudWatchLog
  10. At CloudWatch page.

    • Click the All metrics on the left menu.
    • Click the BooksList_Lambda at the Custom namespaces. CloudWatchMetrics
    • Next, click the env. CloudWatchMetrics
    • Check the staging checkbox -> Click Add to graph button. CloudWatchMetrics
    • After the graph is refreshed, hover the point on the graph.
    • Then, you can see the information. CloudWatchMetrics

So we created a custom metric successfully. Next step we will use it to create a CloudWatch Alarm.