Sitemap
Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Best Practices for AWS Lambda Function Logging

Enhance Visibility and Debugging with Effective Logging

5 min readMar 11, 2023

--

Press enter or click to view image in full size
Photo by Timo C. Dinger on Unsplash

Logging in AWS Lambda functions seems fairly simple and straightforward. All you have to do is print a message and AWS will transfer it to CloudWatch for you, right?

Well, not exactly.

While it might seem like the case, considering that you are taking logs from multiple different functions and sending them to a single centralised system, server-less logging can be tough.

Therefore there are some important considerations to keep in mind to ensure your logging is effective and efficient. In this article, we’ll be covering the best practices for AWS Lambda logging.

Enforce logging standards

This probably doesn’t require a deep explanation. Using a standardised log format across your lambda functions can save you a lot of time and headaches when debugging your application or aggregating logs with 3rd party tools and platforms.

This topic presents a choice between plain text logging and JSON. Although JSON logging is generally recommended over plain text, depending on your specific use case, plain text logging may be sufficient.

However, to harness the full potential of CloudWatch or any another log aggregation platform, it is advisable to use JSON. More bout this in the JSON section of this article.

To log or not to log

Depending on your AWS region the price for CloudWatch log ingression ranges between 0.50$ to 0.80$ per Gb.

While this not might seem like much if you're working with an application that does not face high loads, it definitely stacks up when you're dealing with millions of invocations and logs.

Apart from your own log, lambda also generates START, END and REPORT messages on every execution. These combined together are around 300 Bytes of extra data ingested for each function invocation.

Example:

START RequestId: a61709e4-820c-4cab-b2fb-643344b64799 Version: $LATEST
END RequestId: a61709e4-820c-4cab-b2fb-643344b64799
REPORT RequestId: a61709e4-820c-4cab-b2fb-643344b64799 Duration: 7.21 ms Billed Duration: 8 ms Memory Size: 128 MB Max Memory Used: 67 MB Init Duration: 207.81 ms

Having to be aware of your log sizes is especially true when logging complete events like API Gateway proxy event or EventBridge events that depending on your data can get quite large.

Let's take an example of the following API Gateway proxy event:

{
"version": "2.0",
"routeKey": "ANY /nodejs-apig-function-1G3XMPLZXVXYI",
"rawPath": "/default/nodejs-apig-function-1G3XMPLZXVXYI",
"rawQueryString": "",
"cookies": [
"s_fid=7AABXMPL1AFD9BBF-0643XMPL09956DE2",
"regStatus=pre-register"
],
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-encoding": "gzip, deflate, br"
},
"requestContext": {
"accountId": "123456789012",
"apiId": "r3pmxmplak",
"domainName": "r3pmxmplak.execute-api.us-east-2.amazonaws.com",
"domainPrefix": "r3pmxmplak",
"http": {
"method": "GET",
"path": "/default/nodejs-apig-function-1G3XMPLZXVXYI",
"protocol": "HTTP/1.1",
"sourceIp": "205.255.255.176",
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"
},
"requestId": "JKJaXmPLvHcESHA=",
"routeKey": "ANY /nodejs-apig-function-1G3XMPLZXVXYI",
"stage": "default",
"time": "10/Mar/2020:05:16:23 +0000",
"timeEpoch": 1583817383220
},
"isBase64Encoded": true
}

Pasting this to https://www.debugbear.com/json-size-analyzer gives us a JSON size of 972B. Combine this with the 300B that lambda generates for each function invocation and we will reach 1270B of ingested data for a single log in an invocation.

Now depending on what kind of application you are dealing with, the load on a single Lambda function can be in a range of hundreds to thousands of requests per minute.

Having 10 functions like this in production then could potentially generate multiple Gb of data daily and could add hundreds of dollars to your AWS Bill.

But hold on!

Money is not the only concern. I strongly advise you against logging the full lambda event in production environment.

Get Stefan Sarmir’s stories in your inbox

Join Medium for free to get updates from this writer.

Depending on what kind of data is your lambda function dealing with, you might be logging sensitive information like users ID Number, phone number, etc. This could be a direct violation of GPDR regulations.

Press enter or click to view image in full size

Logging levels

With all of the above being said, there may be times when you need to log additional information, even if it’s not strictly necessary for production use.

This is especially true when debugging an application. For this, you can use log levels to filter out unnecessary information only keep the information that’s most relevant for the given environment.

Some of the common log levels include DEBUG, INFO, WARN, and ERROR.

There are dozens of out of the box solutions like the widely used logger Winston, so you can either use one of the existing logging libraries or write your own custom logger.

You can use Lambda environment variables to control the log level of your lambda function. Define a LOG_LEVEL environment variable based on the environment your Lambda function runs in, for example INFO for production and DEBUG for development. Use it in your logger configuration to set the log level of your logger.

This way you control the amount of detail you get in specific environments. For example you can get all of the logs in your development environment and only the essential ones in production.

Having the LOG_LEVEL defined in the Lambda functions environment variables also allows you to easily change the LOG_LEVEL value and get instant access to full logs even in production, if you ever need them.

But be carefull!

As I stated before be careful not to log any sensitive user information.

Log retention

If you don't create and configure a Log Group for your Lambda function manually, it might do it for you automatically. However, by default the log retention will be set to forever.

Again, depending on the region you are using the log storage prices may vary between 0.030$ — 0.045$ per Gb. This looks really cheap but again, it can add up over the years and also why would you pay for something that you don't actually need.

So think about how long you need to keep your logs for and don't forget to set your retention rate accordingly.

Does the JSON structure really matter?

Yes, it does. CloudWatch or any other log aggregation platform like Datadog index your logs in order to be able to search them.

Using a JSON format allows you to use this feature to it's full potential and therefore make the debugging experience much better and more efficient. This not only saves you time when looking for what went wrong, but also makes it more enjoyable for you.

By using JSON you keep your data organised and structured. This is important because it makes your data readable, but more importantly it allows you to filter and search by it's inner hierarchy items.

Summary

As we can see even seemingly simple topic as logging has it's intricacies.

If you found this article useful, I'd appreciate a few claps, comment or a subscribe.

Also, If you feel like I've missed something, feel free to let me know!

--

Stefan Sarmir
Stefan Sarmir

Written by Stefan Sarmir

Full-Stack Remote SW Engineer interested in serverless technologies. Developing scalable applications on AWS and Azure platforms.