Grant a Lambda Function access to CloudWatch Logs

avatar

Borislav Hadzhiev

Last updated: Sep 28, 2021

banner

Photo from Unsplash

How to Grant a Lambda Function access to CloudWatch Logs #

To grant a lambda function permissions to log to CloudWatch, we have to attach the AWSLambdaBasicExecutionRole AWS managed policy to the function's execution role. The IAM policy grants permissions for the logs:CreateLogGroup, logs:CreateLogStream and logs:PutLogEvents actions.

To attach the IAM policy to your Lambda function's role:

  1. Open the AWS Lambda console and click on your function's name
  2. Click on the Configuration tab and click on Permissions in the sidebar

click on role

  1. Click on the role's name
  2. In the Permissions tab of the role, click on Add permissions and Attach policies
  3. Filter for AWSLambdaBasicExecutionRole in the search input and click the checkbox next to the first result

attach cloudwatch logs policy

The AWSLambdaBasicExecutionRole managed policy contains the following statement that allows our function to log to CloudWatch:

lambda-cloudwatch-logs.json
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "*" } ] }
  1. Click on the Attach policies button
  1. Invoke your lambda function to generate some logs

  2. In the browser tab of the lambda function, click on the Monitor tab and select View logs in CloudWatch

view logs in cloudwatch

  1. Click on the most recent log stream and you should see the logs of your lambda function
If you still are unable to see any logs being produced, make a small change to the lambda function, e.g. increase its timeout by 1 second or add an extra print statement in the function's code and click on the Deploy button.

To get a better view of the logs, click on the View as text checkbox at the top. It displays the logs as text, rather than a series of collapsible rows:

view logs as text

Note that AWS Lambda automatically creates a log group with the name /aws/lambda/your-lambda-name as long as the function has the necessary permissions.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.