Free Trial

Logging Node.js Lambda Functions with CloudWatch

logging-node-js-lambdaWhen AWS Lambda was introduced in 2014, the first language to be supported was Node.js. When a Node.js function is deployed as an AWS Lambda, it allows for the execution of the function in a highly scalable, event-driven environment. Because the user has no control over the hardware or the systems which execute the function, however, the need for logging Node.js Lambda functions is of utmost importance when it comes to monitoring, as well as diagnosing and troubleshooting problems within the function itself.

This post will consider the options for logging within a Node.js function. It will then briefly outline the process of uploading a Node.js function into a Lambda function, configuring the function to send the logs to Cloudwatch, and viewing those logs following the execution of the Lambda.

Logging with Node.js

Within a Node.js function, logging is accomplished by executing the appropriate log function on the console object. Possible log statements include:

  • console.log()
  • console.error()
  • console.warn()
  • console.info()

In each case, the message to be logged is included as a String argument. If for example the event passed to the function included a parameter called ‘phoneNumber’, and we validated the parameter to ensure that it contained a valid phone number, we could log the validation failure as follows:

console.error(“Invalid phone number passed in: “ + event.phoneNumber);

Sometimes the best way to learn something is to play with it. Let’s create an example Lambda so we can see logging in action. First, we’ll need to set up the environment to execute the function.

Configuring it all in AWS

You’ll need access to an AWS environment in order to complete the following. All of this should be available if you are using the free tier. See Amazon for more information on how to set up a free account.

Once you have an AWS environment you can access, and you have logged in, navigate to the Identity and Access Management (IAM) home page.

You’ll need to set up a role for the Lambda function to execute in the AWS environment. On the IAM home page, you should see a section similar to the one shown below which lists IAM Resources (The number next to each will be 0 if this is a new account.)

logging-nodejs-lambda-sumologic1

Click on the Roles label, and then click on the Create New Role button on the next screen. You’ll need to select a name for the role. In my case, I chose ExecuteLambda as my name. Remember the name you choose, because you’ll need it when creating the function.

logging-nodejs-lambda-sumo-logic

Click on the Next Step button. You’ll now be shown a list of AWS Service Roles. Click the Select button next to AWS Lambda. Filter: Policy Type box, type AWSLambdaExecute. This will limit the list to the policy we need for this role. Check the checkbox next to the AWSLambdaExecute policy as shown below, and then click on Next Step.

logging-nodejs-lambda-sumo-logic-3

You’ll be taken to a review screen, where you can review the new policy to ensure it has what you want, and you can then click on the Create Role button to create the role.

Create Your Lambda Function

Navigate to the Lambda home page at https://console.aws.amazon.com/lambda/home, and click on Create Lambda Function. AWS provides a number of sample configurations you can use. We’re going to be creating a very simple function, so scroll down to the bottom of the page and click on Skip.

AWS also provides the option to configure a trigger for your Lambda function. Since this is just a demo, we’re going to skip that as well. Click on the Next button on the bottom left corner of the page.

Now we get to configure our function. Under Configure function, choose a Name for your function and select the Node.js 4.3 Runtime.

logging-nodejs-lambda-sumo-logic-4

Under Lambda function code, choose Edit code inline from the Code entry type dropdown, and then enter the following in the Code Window.


exports.handler = function(event, context) {
console.log("Phone Number = " + event.phoneNumber);
if (event.phoneNumber.match(/\d/g).length != 10) {
console.error("Invalid phone number passed in: " + event.phoneNumber);
} else {
console.info("Valid Phone Number.")
}
context.done(null, "Phone number validation complete");
}

Under Lambda function handler and role, set the Handler to index.handler, the Role to Choose an Existing role, and for Existing role, select the name of the role you created previously.

Click on Next, review your entries and then click on Create function.

Test the Function and View the Logs

Click on the Test button, and enter the following test data.

logging-nodejs-lambda-sumo-logic-6

Click Save and Test and you should see the test results shown on the bottom of the screen. By default, Lambdas also send their logs to CloudWatch. If you click on the Monitoring tab, you can click on the View logs in CloudWatch link to view the logs in CloudWatch.

logging-nodejs-lambda-sumo-logic-7

If you return to the Lambda code page, you can click on Actions, select Configure test event and then enter different data to see how the result changes. Since the validator only checks to ensure that the phone number contains 10 numbers, you can simply try it with 555-1234 as the phone number and watch it fail.

logging-nodejs-lambda-sumo-logic-8

Please note that this example is provided solely to illustrate logging within a Node.js function, and should not be used as an actual validation function for phone numbers.

About the Author

Mike Mackrory is a Global citizen who has settled down in the Pacific Northwest – for now. By day he works as a Senior Engineer on a Quality Engineering team and by night he writes, consults on several web-based projects and runs a marginally successful eBay sticker business. When he’s not tapping on the keys, he can be found hiking, fishing and exploring both the urban and rural landscape with his kids. Always happy to help out another developer, he has a definite preference for helping those who bring gifts of gourmet donuts, craft beer and/or Single-malt Scotch.

Logging Node.js Lambda Functions with CloudWatch is published by the Sumo Logic DevOps Community. If you’d like to learn more or contribute, visit devops.sumologic.com. Also, be sure to check out Sumo Logic Developers for free tools and code that will enable you to monitor and troubleshoot applications from code to production.

Get Started Today!

Sign up for your FREE Sumo Logic Trial.

Free Trial
“Sumo Logic brings everything together into one interface 
where we Hudl can quickly scan across 1,000 servers across and gigabytes of logs and quickly identify problems. It’s awesome software 
and awesome support.”

Jon Dokuli,
VP of Engineering

Sign up for your 30 day free trial!*
Sign up for Sumo Logic Free
  • No credit card required to sign-up
  • Create your account in minutes
  • No expiration date*
  • *After 30 day trial period, reverts to Sumo Logic Free
    View All Pricing Options
    Already have an account? Login