# 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](https://zato.io/docs/dev/examples/cloud/aws/index.html) in the Dashboard, and the metrics client is available under `conn.cloudwatch` while the logs API is a separate service, available under `conn.logs`.

## Publishing custom metrics {#publishing-custom-metrics}

```python
# -*- 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 {#reading-metric-statistics}

```python
# -*- 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 {#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.

```python
# -*- 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}
```

## More resources {#more-resources}

- [AWS integrations overview](https://zato.io/docs/dev/examples/cloud/aws/index.html)
- [AWS tutorial](https://zato.io/docs/dev/examples/cloud/aws/tutorial.html)
- [boto3 CloudWatch reference](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudwatch.html)

## Learn more {#learn-more}

- [Development documentation](https://zato.io/docs/dev/) - The complete reference for writing services
- [Requests and responses](https://zato.io/docs/dev/request-response/) - What a service receives, what it returns and how both are structured
- [Integration examples](https://zato.io/docs/dev/examples/) - Ready-made code for the systems you are likely to connect to
- [IDE and debugging](https://zato.io/docs/dev/ide/) - Write services in the Dashboard or in your own editor
- [Data models](https://zato.io/docs/dev/model/) - Declare inputs and outputs and have them validated for you
- [In-depth API tutorial](https://zato.io/tutorials/main/01.html) - The full platform tutorial, from installation to production patterns
