0
0
AwsHow-ToBeginner · 4 min read

How to Log in AWS Lambda Using CloudWatch Logs

To log in AWS Lambda using CloudWatch, simply use console.log() (Node.js) or the equivalent logging method in your Lambda code. AWS Lambda automatically sends these logs to CloudWatch Logs, where you can view and monitor them in the AWS Management Console.
📐

Syntax

In AWS Lambda, logging is done by writing messages to the standard output or error streams. These messages are automatically captured and sent to CloudWatch Logs.

For example, in Node.js Lambda functions, use console.log('message') to log information.

Each log entry includes a timestamp and the message you provide.

javascript
console.log('This is a log message');
💻

Example

This example shows a simple AWS Lambda function in Node.js that logs a message to CloudWatch Logs when invoked.

When you run this Lambda, the message will appear in the CloudWatch Logs console under the Lambda's log group.

javascript
exports.handler = async (event) => {
  console.log('Lambda function started');
  // Your function logic here
  console.log('Processing event:', JSON.stringify(event));
  return { statusCode: 200, body: 'Success' };
};
Output
Log entries in CloudWatch Logs: [Timestamp] Lambda function started [Timestamp] Processing event: { ...event data... }
⚠️

Common Pitfalls

  • Not checking CloudWatch Logs permissions: Your Lambda's execution role must have logs:CreateLogGroup, logs:CreateLogStream, and logs:PutLogEvents permissions to send logs.
  • Expecting logs in the Lambda console only: Logs are visible in the CloudWatch Logs console, not directly in the Lambda console.
  • Using print statements in unsupported languages: Use the language's standard logging method (e.g., console.log for Node.js, print for Python).
plaintext
/* Wrong: Missing permissions in Lambda role */
// Lambda function logs won't appear in CloudWatch without proper IAM permissions.

/* Right: Attach AWS managed policy AWSLambdaBasicExecutionRole */
// This policy includes necessary CloudWatch Logs permissions.
📊

Quick Reference

StepActionDetails
1Write logs in Lambda codeUse console.log() or equivalent to output messages.
2Ensure IAM permissionsLambda execution role needs CloudWatch Logs permissions.
3Invoke LambdaRun your Lambda function to generate logs.
4View logs in CloudWatchGo to AWS Console > CloudWatch > Logs > Log groups > /aws/lambda/your-function-name.

Key Takeaways

Use your Lambda language's standard logging method to send logs to CloudWatch automatically.
Ensure your Lambda execution role has permissions to write logs to CloudWatch Logs.
View logs in the CloudWatch Logs console under your Lambda's log group.
Logs help you monitor and debug your Lambda functions effectively.
CloudWatch Logs captures all standard output and error streams from Lambda.