CloudWatch metric cung cấp một số số liệu cho các hàm Lambda như số lần hàm được thực thi, thời gian thực thi mỗi lần, tỷ lệ lỗi và số lần bị giới hạn. Để xem các số liệu của một hàm nhất định, chúng ta thực hiện các bước sau.

Tại trang books_list.

Tiếp theo, chúng ta sẽ tạo một số liệu tùy chỉnh mới để tổng hợp số lần truy cập vào DynamoDB bị lỗi. Tại trang books_list.
Nhấn tab Code.
Sao chép đoạn mã sau.
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}')
Nhấn nút Deploy.

Tại trang books_list.

Tại trang fcaj-book-store-BooksListRole-….

Tại trang Step 1: Modify permissions in BooksListRolePolicy0.
Nhấn tab JSON.
Sao chép đoạn mã sau vào Policy editor.
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "cloudwatch:PutMetricData",
"Resource": "*"
},

Cuộn xuống cuối trang và nhấn nút Next.

Tại trang Step 2: Review and save.


Mở Postman để gọi lại API, lỗi trả về là Internal server error.

Quay lại trang hàm Lambda books_list.

Tại trang CloudWatch.




Vậy là chúng ta đã tạo thành công một số liệu tùy chỉnh. Bước tiếp theo chúng ta sẽ sử dụng nó để tạo một CloudWatch Alarm.