To add custom timeout logging to an AWS Lambda function written in Node.js, you can use the context.callbackWaitsForEmptyEventLoop property and the console object to log messages. The context.callbackWaitsForEmptyEventLoop property allows you to control whether the Lambda function should wait for the event loop to be empty before it exits.

Here's an example of how you can implement custom timeout logging in a Node.js AWS Lambda function:

exports.handler = async (event, context) => { // Increase the Lambda function timeout to 30 seconds (if needed) context.callbackWaitsForEmptyEventLoop = false; // Your main Lambda function logic goes here try { // Some long-running task (e.g., database query, API call, etc.) await performLongRunningTask(); // Logging the success message console.log('Function execution completed successfully.'); // If the function completes successfully, call the callback to end the function context.done(null, 'Function execution completed successfully.'); } catch (error) { // Logging the error message console.error('Error occurred during function execution:', error); // If an error occurs, call the callback with the error to end the function context.done(error); } };

In this example, we set context.callbackWaitsForEmptyEventLoop to false to tell AWS Lambda not to wait for the event loop to be empty before it exits. This allows the function to complete immediately when the main logic is done, even if there are pending asynchronous tasks in the event loop.

After the main logic completes (either successfully or with an error), we log a success or error message using the console.log and console.error functions, respectively. This allows you to track the execution progress and any potential errors in CloudWatch logs.

Additionally, we call context.done with an error object if an error occurs during function execution. This signals to AWS Lambda that the function should terminate due to an error, and the error message will be logged in the CloudWatch logs.

Remember that if you set context.callbackWaitsForEmptyEventLoop to false, you need to ensure that all asynchronous operations in your Lambda function have completed before the function ends, or you may risk incomplete execution of your code. In the example above, the await performLongRunningTask(); ensures that the long-running task is completed before the function ends.

By using context.callbackWaitsForEmptyEventLoop and the console object, you can implement custom timeout logging in your AWS Lambda function and have better control over the function's execution.

Have questions or queries?
Get in Touch