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, andlogs:PutLogEventspermissions 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.logfor Node.js,printfor 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
| Step | Action | Details |
|---|---|---|
| 1 | Write logs in Lambda code | Use console.log() or equivalent to output messages. |
| 2 | Ensure IAM permissions | Lambda execution role needs CloudWatch Logs permissions. |
| 3 | Invoke Lambda | Run your Lambda function to generate logs. |
| 4 | View logs in CloudWatch | Go 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.