【发布时间】:2020-03-13 18:34:59
【问题描述】:
import boto3
from datetime import timedelta
from datetime import datetime
def lambda_handler(event, context):
# TODO implement
region = 'us-east-1'
cwWindow = 60
cloudwatch = boto3.client('cloudwatch', region_name='us-east-1')
# List metrics through the pagination interface
response = cloudwatch.get_metric_statistics(
Namespace='AWS/EC2',
MetricName='CPUUtilization',
Dimensions=[
{
'Name': 'InstanceId',
'Value': 'i-09deabee19c5fc46d'
},
],
StartTime=datetime.utcnow() - timedelta(minutes = 60),
EndTime=datetime.utcnow(),
Period=300,
Statistics=['Average', 'Maximum'],
Unit='Percent'
)
return response
我们已经编写了函数来获取我的 ec2 实例的 CPUUtilization 指标,但出现以下错误“datetime.datetime(2020, 3, 11, 12, 3, tzinfo=tzlocal()) is not JSON serializable ":
Response
{
"errorType": "TypeError",
"errorMessage": "datetime.datetime(2020, 3, 11, 12, 3, tzinfo=tzlocal()) is not JSON serializable",
"stackTrace": [
" File \"/var/lang/lib/python3.6/json/__init__.py\", line 238, in dumps\n **kw).encode(obj)\n",
" File \"/var/lang/lib/python3.6/json/encoder.py\", line 199, in encode\n chunks = self.iterencode(o, _one_shot=True)\n",
" File \"/var/lang/lib/python3.6/json/encoder.py\", line 257, in iterencode\n return _iterencode(o, 0)\n",
" File \"/var/runtime/awslambda/bootstrap.py\", line 149, in decimal_serializer\n raise TypeError(repr(o) + \" is not JSON serializable\")\n"
]
}
Function Logs
An error occurred during JSON serialization of response: datetime.datetime(2020, 3, 11, 12, 3, tzinfo=tzlocal()) is not JSON serializable
Traceback (most recent call last):
File "/var/lang/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/var/lang/lib/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/var/lang/lib/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/var/runtime/awslambda/bootstrap.py", line 149, in decimal_serializer
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2020, 3, 11, 12, 3, tzinfo=tzlocal()) is not JSON serializable
Request ID
057aa5a4-74f6-1881-a024-74f6c2134125
我们使用与 boto3 文档中所述相同的格式,但仍然出现错误。如果有人有boto3的cloudwatch客户端经验。需要帮助。
【问题讨论】:
-
无法重现该问题。你用的是什么python版本?
-
我使用的是 python 3.6。你用过boto3模块的cloudwatch客户端吗?
-
是的。但现在我刚刚用我的实例检查了你的代码。没有发现问题。
-
它是否提供数据点?你能发布你的代码和回复吗?您使用的是哪个 IDE?我正在尝试使用 cloud9。
-
是的。这是一个示例输出:pastebin.com/raw/DsQv6eJ0
标签: python amazon-web-services datetime boto3 amazon-cloudwatch-metrics