How to get cloudwatch metrics of a lambda using boto3 and lambda python?
I have a Lambda in which I'm trying to get the metrics (especifically the number of invokes) from Cloudwatch of another Lambda. I was following the docs from https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudwatch.html#CloudWatch.Client.get_metric_data and some other examples I found around the internet, but I'm unable to make it work. When I run the code, the response appears with null values, so I might be missed something.
For example, in the code below, I'm trying to get the metrics from November when I was doing some testing with the Lambda (called "lambda-function-to-analyze") I wish to analyze.
def get_metric_data():
cloudwatch = boto3.client('cloudwatch')
date = datetime.now()
first = date.replace(day=1)
last = date.replace(day = calendar.monthrange(date.year, date.month)[1])
print('first: ', first)
print('last: ', last)
targetGroupARN='arn:aws:lambda:us-east-1:1234567890:function:lambda-function-to-analyze'
tgarray=targetGroupARN.split(':')
target=tgarray[-1]
print(target)
response = cloudwatch.get_metric_data(
MetricDataQueries=[
{
'Id': 'myrequest',
'MetricStat': {
'Metric': {
'Namespace': 'Invocations',
'MetricName': 'Number of invokes',
'Dimensions': [
{
'Name': 'lambda',
'Value': target
},
]
},
'Period': 300,
'Stat': 'Sum',
# 'Unit': 'Count'
}
},
],
# StartTime=datetime(first.year, first.month, first.day),
StartTime=datetime(2021, 11, 1),
# EndTime=datetime(last.year, last.month, last.day),
EndTime=datetime(2021, 11, 30),
)
print(response)
return response
Solution 1:
I think the main problem is your MetricName
field. Perhaps try changing your Namespace
and MetricName
like so:
{
"Namespace": "AWS/Lambda",
"MetricName": "Invocations",
...
}