Loki: collecting logs from CloudWatch Logs using Lambda Promtail
Tags: aws, monitoring, devops
Published: 2023-07-08 12:29:10

---
title: Loki: collecting logs from CloudWatch Logs using Lambda Promtail
published: true
date: 2023-05-20 12:39:50 UTC
tags: aws,monitoring,devops
canonical_url: https://rtfm.co.ua/en/loki-collecting-logs-from-cloudwatch-logs-using-lambda-promtail/
---

![](https://cdn-images-1.medium.com/max/538/1*AbuS5UNh29b7qbh5diEqgA.png)

Collecting logs in Grafana Loki with Kubernetes is very simple — we just launch Promtail in DaemonSet, configure it to read all data from `/var/logs` - and that's it (in fact, we don't specify anything at all - everything works out of the box from the Helm chart).

But what about CloudWatch Logs? On my new project, we have a bunch of AWS Lambdas, API Gateways, etc., and they all write logs to CloudWatch.

As for Lambda, it would be possible to use the [Lambda Telemetry API](https://docs.aws.amazon.com/lambda/latest/dg/telemetry-api.html) and write logs from a function directly to Loki, see [Building an AWS Lambda Telemetry API extension for direct logging to Grafana Loki](https://dev.to/aws-builders/building-an-aws-lambda-telemetry-api-extension-for-direct-logging-to-grafana-loki-de4), and maybe later we will also use this approach, but now we already have a bunch of logs from other services in CloudWatch, and we still need to read them.

There is still an option to install CloudWatch as a data source in Grafana, and simply [use](https://grafana.com/docs/grafana-cloud/data-configuration/integrations/integration-reference/integration-cloudwatch-logs/) the logs from the Grafana interface, and probably even have Grafana alerts from these logs, but sooner or later Kubernetes or simply EC2 instances will appear, and it will be necessary to collect logs from them, so I’d like immediately do everything with Loki, especially since it has excellent [LogQL](https://rtfm.co.ua/en/draft-grafana-loki-logql-for-logs-and-creating-metrics-for-alerts/), and is much more flexibility in creating labels and alerts.

In this case, we can use [Lambda Promtail](https://grafana.com/docs/loki/latest/clients/lambda-promtail/) from Grafana itself, and it will work as follows:

- some Lambda function (for example) writes a log to the CloudWatch Log Group
- in the Log Group, we will have a [Subscription filter](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html), which will send logs to another Lambda function — Lambda Promtail itself
- and Lambda Promtail will forward them to the Loki instance

So, today we will create a test Lambda function that will write logs, and we will start a Lambda Promtail that will send logs to Grafana Loki, which is already present.

What you need to pay attention to is the amount of data that will be written, because as always with AWS, it is quite easy to run into money, so it is good to have [AWS Budgets](https://aws.amazon.com/aws-cost-management/aws-budgets/) configured to receive an alert in case of unexpected expenses.

Also, keep in mind that Loki will need to be exposed on port 3100, so it’s best to have Lambda Promtail in the same VPC running Grafana itself and/or have some sort of NGINX with HTTP authentication.

### Testing Lambda for creating logs

Let’s create a function, let it be in Python:

![](https://cdn-images-1.medium.com/max/751/0*WGyvivlGdfcazszT.png)

In the code of the function, we will add several `print()` to create records in its log:

```
import json
import os

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
    print('## ENVIRONMENT VARIABLES')
    print(os.environ['AWS_LAMBDA_LOG_GROUP_NAME'])
    print(os.environ['AWS_LAMBDA_LOG_STREAM_NAME'])
    print('## EVENT')
    print(event)
```

Press Test to create a test event, the data in the Event JSON field is not important now, we just specify the name of the event and save it:

![](https://cdn-images-1.medium.com/max/806/0*MwXDY5Z3EzXeySxd.png)

Press Test again — the function has been executed, and the Function Logs have appeared:

![](https://cdn-images-1.medium.com/max/1024/0*MrWkYJ7aNqgKxg9P.png)

Go to Monitor > Logs, and from there to the CloudWatch Logs:

![](https://cdn-images-1.medium.com/max/977/0*86GgjrUvCNGFAZFB.png)

And check that there are Log events:

![](https://cdn-images-1.medium.com/max/1024/0*e_nWkz3_jU9qquvR.png)

That’s all here, now we can move on to Lambda Promtail.

### Running Lambda Promtail

There is a ready-to-use [Terraform](https://github.com/grafana/loki/blob/main/tools/lambda-promtail/main.tf) project and even a [Cloudformation](https://github.com/grafana/loki/blob/main/tools/lambda-promtail/template.yaml) template, so you can use them. The only thing is that in Terraform it is necessary to fix the creation `resource "aws_iam_role_policy_attachment" "lambda_sqs_execution"` in the file `sqs.tf`, because the role is called there `role = aws_iam_role.iam_for_lambda.name`, but in the `main.tf` it is called `resource "aws_iam_role" "this"`.

In everything else, Terraform works — we just set values ​​for the variables in `variabels.tf` - the `write_address`, `log_group_names`, and `lambda_promtail_image`, and you can create resources.

However, I still prefer to create everything manually for the first time in order to understand better what and how it will work.

#### Docker image and Elastic Container Service

First, we will prepare a Docker image, because for some reason it is impossible to run AWS Lambda from the [public Grafana ECR](https://gallery.ecr.aws/grafana/lambda-promtail), although I did not find such a limitation anywhere in the documentation.

Go to ECR, and create a repository:

![](https://cdn-images-1.medium.com/max/789/0*A8VvQmSHB2grMt5r.jpg)

Download the public image from Grafana:

```
$ docker pull public.ecr.aws/grafana/lambda-promtail:main
```

Re-tag it with your repository:

```
$ docker tag public.ecr.aws/grafana/lambda-promtail:main 264***286.dkr.ecr.eu-central-1.amazonaws.com/lambda-promtail-writer:latest
```

Log in to ECR — specify `--profile`, if it's not a default and an AWS Region:

```
$ aws --profile setevoy ecr get-login-password --region eu-central-1 | docker login --username AWS --password-stdin 264***286.dkr.ecr.eu-central-1.amazonaws.com
…
Login Succeeded
```

Push your image there:

```
$ docker push 264***286.dkr.ecr.eu-central-1.amazonaws.com/lambda-promtail-writer:latest
```

Let’s move on to Lambda.

#### Creating Lambda Promtail function

Create a new function, select Container image, and specify the URI of the image that was pushed above:

![](https://cdn-images-1.medium.com/max/1024/0*f9MdXf_OGAlU-2Kb.png)

Go to Configuration > Environment variables, and set the minimum required variables:

- `EXTRA_LABELS`: the tags/labels that will be added to Loki, are specified here in the format of _labelname,labelvalue_
- `WRITE_ADDRESS`: the Loki address with `https://` and URI `/loki/api/v1/push`

![](https://cdn-images-1.medium.com/max/852/0*1S5gzkWTX_QgrrH-.jpg)

#### CloudWatch Log Group Subscription filters configuration

Return to the CloudWatch Log Group, which contained our test logs, and in the Subscription filters tab add a new subscription for the Lambda function (see [Using CloudWatch Logs subscription filters](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html) or [How can I configure a CloudWatch subscription filter to invoke my Lambda function?](https://repost.aws/knowledge-center/lambda-cloudwatch-filter) ):

![](https://cdn-images-1.medium.com/max/1024/0*pZL7EvxZWJjvQ_mu.png)

Choose a function to which we will stream logs, and if necessary, specify a filter in the Configure log format and filters field, which will be used to choose what exactly to send to Lambda, not to send all the records.

At this moment we don’t need it, so we set _Other_ in the Log format and leave the Subscription filter pattern empty.

In the Subscription filter name, specify the name of the filter itself:

![](https://cdn-images-1.medium.com/max/764/0*L6qzqsG0ri1O6dzU.png)

Save — press Start streaming, return to the `write-logs` Lambda and press _Test_ several times to create more records in the CloudWatch Log Group That should trigger the function `lambda-promtail-testing` and transfer the data it will send to Loki.

Check the `lambda-promtail-testing` function - there should be executions in the Monitoring:

![](https://cdn-images-1.medium.com/max/1024/0*7C2mmXVXiJaKGcRH.png)

In the case of Errors, the Logs tab contains a link to the CloudWatch Log for this function, which will describe the error.

If everything is Success, then we should already see a new label in the Loki, and we can use it to select logs from the function `write-logs`:

![](https://cdn-images-1.medium.com/max/1024/0*a-83md-AWTTH4lmZ.jpg)

Done.

On the Grafana [documentation page](https://grafana.com/docs/loki/latest/clients/lambda-promtail/#examples), they also write that “_Or, have lambda-promtail write to Promtail and use_ [_pipeline stages_](https://grafana.com/docs/loki/latest/clients/promtail/stages/drop/) “, but I wasn’t able to find a possibility to write data via gRPC or HTTP in Promtail, although this idea was back in 2020, but it is still in Draft — [Promtail Push ](https://grafana.com/docs/loki/latest/design-documents/2020-02-promtail-push-api/)[API](https://grafana.com/docs/loki/latest/design-documents/2020-02-promtail-push-api/).

_Originally published at_ [_RTFM: Linux, DevOps, and system administration_](https://rtfm.co.ua/en/loki-collecting-logs-from-cloudwatch-logs-using-lambda-promtail/)_._

* * *