aws rds 发送慢日志邮件
AWS RDS 不提供主机文件访问权限,因此无法直接访问数据库日志。但是,AWS RDS提供将数据库日志导出到CloudWatch Logs的功能,您可以访问该功能进行监控报警。
解决方案概述
操作步骤:
- RDS开通慢日志查询
- 导入到CloudWatch Log
- 启用订阅SNS
- Lambda代码开发
import sys
import re
import boto3
import os
# Reading the cloudwatch log data
def lambda_handler(event, context):
# 日志被用 zip 压缩,並以 base64 编码,所以要先解码
cloudwatch_event = event["awslogs"]["data"]
print(cloudwatch_event)
decode_base64 = base64.b64decode(cloudwatch_event)
decompress_data = gzip.decompress(decode_base64)
cloud_log_ = json.loads(decompress_data)
cloud_log_data=cloud_log_['logEvents'][0]['message']
print(cloud_log_data)
# Reading Query_time
result = re.findall(r'Query_time: \d+\.\d+', cloud_log_data)
#print(result[0])
data_list = result[0].split(":")[1]
#print(data_list)
data_time = float(data_list)
# # Sends an SNS notification with the slow log information
if data_time > 10:
SNSClient = boto3.client('sns')
response = SNSClient.publish(TopicArn='arn:aws:sns:us-east-2:1234148497:Default_CloudWatch_Alarms_Topic',Message=cloud_log_data,Subject='rds_slow_log')
print(response)
权限帮助链接: > https://aws.amazon.com/cn/premiumsupport/knowledge-center/sns-authorization-error-lambda-function/