How To Use CloudWatch To Debug Serverless Lambda Functions In AWS

How To Use CloudWatch To Debug Serverless Lambda Functions In AWS

?? Hello there, welcome to The Serverless Spotlight!

In this week's edition, we're going to see how to work with an extremely common tool - CloudWatch - to understand and debug errors coming from our serverless Lambda functions.


What is AWS CloudWatch?

Whenever you work with the Lambda service, you will need to be able to view and monitor logs.

Whether you have errors, server responses or other monitoring needs, CloudWatch is an invaluable tool to let you understand what is going on with your AWS services from a logging point of view.

In this article, we'll discuss specifically how to use CloudWatch with your Lambda functions and look at debugging serverless functions as well.

Lambda Function

Let's start by creating a simple Lambda function and simulate an error response.

In your AWS account, navigate to the Lambda service.

Click on the Create function button at the top.

Use the following configuration for your Lambda function:

  • Choose Author from scratch option
  • Name the function "simulate-error-response".
  • Use the Node JS 20.x runtime
  • Add permissions to invoke CloudWatch

Creating a Lambda function

Create the function.

You should now see the Lambda function page:

In the Code editor below, you will see some demo code. Overwrite it with the following code:

import dbs from "dbs";

export const handler = async (event) => {
  try {
    const params = {name: "John"};
    const simError = dbs.query(params);

    const response = {
      statusCode: 200,
      body: JSON.stringify('Hello from Lambda!'),
    };
  }
  catch (error) {
     const response = {
     statusCode: 502, 
     body: JSON.stringify("An error occured: ", error)
    }
  }
};
        
Code in the Lambda browser IDE

The code above has an error but let's pretend it was a lot more complex and we couldn't find the error.

When we invoke this function (from our frontend or another way), we'll get an error.

How can we view this error in detail to efficiently be able to debug it?

Monitoring With CloudWatch

This is where CloudWatch comes in.

CloudWatch is of course much more powerful than simple Lambda code debugging, but it is one way for us to efficiently debug complex serverless code right in the cloud.

From the code editor, scroll up top the menu bar right above the editor where you will see Monitor.

Click on the View CloudWatch logs button.

This will open a new browser tab with the CloudWatch service.

All of the logs for this Lambda function will be stored here.

Scroll down to Log stream. Here you will find the log streams ordered by most recent.

Click on the latest one - that should be the last function invocation we made.

That will open up the log event details.

Here you can view every log event that took place before, during and after the function invocation.

As you can see on the second line we have an undefined error.

Clicking on that line will expand the error details and give us the stack trace of the error.

The error is telling us "Cannot find package 'dbs' imported from /var/task/index.mjs".

It correctly notifies us that the import for 'dbs' is not defined.

The log event can also output console log messages, error exceptions and more logging that we need from our Lambda function.

Other CloudWatch Use Cases

  1. Billing Metrics - you can use CloudWatch to setup billing alarms so you can be notified when a certain AWS service's monthly pricing is approaching or has exceeded a cost threshold you define. I wrote a guide to help you do this here.
  2. Proactive Alerting - You can also set alarms for anomalies like high error rates, increased latency or low free disk space.
  3. Application Metrics - you can monitor metrics like CPU utilization, memory usage, I/O operations for EC2 instances, RDS databases and other AWS services.
  4. Troubleshooting & Analysis - collect application logs like HTTP request logs, database queries and API errors.
  5. Custom Dashboards - create custom dashboards to see metrics from multiple AWS services. E.g. monitor Lambda calls, DynamoDB throughput and S3 requests.
  6. And many more use cases that you can read about here.

Conclusion

AWS CloudWatch is a powerful tool for monitoring and debugging your AWS Lambda functions, offering real-time logging and performance insights.

In this guide, I walk you through setting up a Lambda function, simulating an error, and using CloudWatch logs to trace and resolve issues efficiently.

Besides for debugging, CloudWatch supports various use cases like billing alerts, proactive anomaly detection, and custom dashboards for comprehensive application monitoring.


?? My name is Uriel Bitton and I hope you learned something in this edition of The Serverless Spotlight

?? You can share the article with your network to help others learn as well.

?? If you want to learn how to save money in the cloud you can subscribe to my brand new newsletter The Cloud Economist.

?? I hope to see you in next week's edition!

Hammond Burke

Software Engineer and creator of awesome things!

1 周

I use it schedule automated functions by triggering Lambda on a schedule.

Joel Wembo

Cloud Solutions Architect @ prodxcloud

1 周

Very informative

要查看或添加评论,请登录