Decorate the Python function - Metrics
Tags: aws, serverless, observability, devops
Published: 2021-12-05 20:15:56

---
title: Decorate the Python function - Metrics
series: [Lambda Observability]
published: true
description: Use the AWS Lambda Powertools to decorate Python functions
tags: #AWS #Serverless #Observability #DevOps
cover_image: https://www.pawelpiwosz.net/assets/lambdaObservability/sherlock-holmes.jpg
---

## Recap

In last episode we instrumented our function with traces. Now we will do the same thing with metrics.

## Decorate the handler

### Metrics

Like with traces we need to import proper functionality from the powertools library.

First, let's remember, in the SAM template we need to have two obligatory variables:

```yaml
POWERTOOLS_SERVICE_NAME: simpleFunctionService
POWERTOOLS_METRICS_NAMESPACE: simpleFunctionMetrics
```

`POWERTOOLS_SERVICE_NAME` we set previously. `POWERTOOLS_METRICS_NAMESPACE` gives us the possibility to collect all related metrics under one container. We can add custom dimensions later.

***

Currently we have this part of the code

```python
from aws_lambda_powertools import Tracer

tracer = Tracer()
```

Let's update it with metrics.

```python
from aws_lambda_powertools import Tracer, Metrics

tracer = Tracer()
metrics = Metrics()
```

***

At this moment we are ready to decorate the handler with metrics decorator:

```python
@metrics.log_metrics(capture_cold_start_metric=True)
@tracer.capture_lambda_handler
def handler(event, context):
    """ A very simple Lambda function """
```

All right, let's deploy it and let's take a look on the CloudWatch Metrics console!

***

As we can easily see, the new Custom Metrics appeared.

![Custom metrics](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics1.jpg)

Click the `simpleFunctionMetrics`, then click `function_name, service` (we should see that we have 1 metrics there). We can select `ColdStart` metrics now. We should see at least one coldstart is registered.

![Custom metrics, coldstart](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics2.jpg)

***

Looks perfect!

### Custom metrics

Now it is the time to add the custom metrics. But before we start, please remember, if we add metrics outside the handler, in the global scope, it will be used during the cold start only! Anyway, we will test it to see how it works.

#### Import MetricUnit

According to [documentation](https://awslabs.github.io/aws-lambda-powertools-python/latest/core/metrics/): MetricUnit enum facilitate finding a supported metric unit by CloudWatch. Alternatively, you can pass the value as a string if you already know them e.g. "Count".

We use this approach, therefore we need to import one more element from library.

```python
from aws_lambda_powertools.metrics import MetricUnit
```

#### Custom metrics for coldstart

Now, before we define any function, let's put this part of the code:

```python
""" This is the coldstart metrics only"""
metrics.add_dimension(name="Execution", value="ColdStart")
metrics.add_metric(name="ColdStarted", unit=MetricUnit.Count, value=1)
```

This will create a custom metrics which should be executed only during cold start.

Ok, after deployment I executed the function multiple times.

Let's take a look on CloudWatch Logs.

![CloudWatch Logs for instrumented Lambda](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics3.jpg)

As we can clearly see the idea of instrumenting the custom metrics for coldstart only is successsfull. We see multiple executions but only one is instrumented in logs.

Let's see the metrics then. When we go to CloudWatch Metrics, we can see 2 metrics there.

![Custom metrics, coldstart](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics4.jpg)

Let's click it. Now we have two dimensions. The default one, and the one we created - `Executions`.

![Custom metrics, coldstart](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics5.jpg)

Let's finally go inside and graph the metrics. I switched the display method to numbers as it shows the effect better.

![Custom metrics, coldstart](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics6.jpg)

### Execution metrics

Now it is the time to instrument the functionality with custom metrics. What we want to achieve is to see how many times the specific function was executed.

Let's add this part

```python
metrics.add_dimension(name="Execution", value="Functionality")
metrics.add_metric(name="Handler", unit=MetricUnit.Count, value=1)
```

Into the handler, and this

```python
metrics.add_metric(name="sumNumbers", unit=MetricUnit.Count, value=1)
```

Into each function. Please remember to change the `name` for each function.

After deployment and a few executions we should see something like this:

![Custom metrics](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics7.jpg)

When we click...

![Custom metrics](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics8.jpg)

And click again...

![Custom metrics](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics9.jpg)

So, we have more metrics now!

Let's take a look on the CloudWatch Metrics dashboard now. The display is very similar like it was before, the only one thing which I changed was the aggreggation - from `average` to `sum`.

![Custom metrics](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics10.jpg)

Ok, after many executions this is what you can get through CloudWatch. It is not perfect. But we will work on it... later :)

![Custom metrics](https://www.pawelpiwosz.net/assets/lambdaObservability/Powertools-metrics11.jpg)

***

Cover image by <a href="https://pixabay.com/users/422737-422737/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=462957">Hebi B.</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=462957">Pixabay</a>