Python AWS CloudWatch
CloudWatch custom metrics, metric statistics and log events from Python services.
Zato lets you work with Amazon CloudWatch directly from your Python services. You create an AWS connection in the Dashboard, and the metrics client is available under conn.cloudwatch while the logs API lives in its own service, under conn.logs.
Publishing custom metrics
# -*- coding: utf-8 -*-
# Zato
from zato.server.service import Service
class ReportOrdersProcessed(Service):
input = 'count'
def handle(self):
# Get the connection by its Dashboard name
conn = self.aws['My AWS']
# Publish a custom metric data point
conn.cloudwatch.put_metric_data(
Namespace='OrderProcessing',
MetricData=[{
'MetricName': 'OrdersProcessed',
'Value': self.request.input.count,
'Unit': 'Count',
}],
)
Reading metric statistics
# -*- coding: utf-8 -*-
# stdlib
from datetime import datetime, timedelta
# Zato
from zato.server.service import Service
class GetOrderStatistics(Service):
def handle(self):
conn = self.aws['My AWS']
end_time = datetime.utcnow()
start_time = end_time - timedelta(hours=24)
# The sum of orders processed per hour over the last day
response = conn.cloudwatch.get_metric_statistics(
Namespace='OrderProcessing',
MetricName='OrdersProcessed',
StartTime=start_time,
EndTime=end_time,
Period=3600,
Statistics=['Sum'],
)
self.response.payload = {'datapoints': response['Datapoints']}
Reading log events
CloudWatch Logs is a separate AWS service, so it has its own client - conn.logs, the same one that boto3.client('logs') returns.
# -*- coding: utf-8 -*-
# Zato
from zato.server.service import Service
class GetRecentApplicationLogs(Service):
input = 'log_group', 'log_stream'
def handle(self):
conn = self.aws['My AWS']
# The most recent events from one log stream
response = conn.logs.get_log_events(
logGroupName=self.request.input.log_group,
logStreamName=self.request.input.log_stream,
limit=100,
)
messages = []
for event in response['events']:
messages.append(event['message'])
self.response.payload = {'messages': messages}