🐾How to write logs from Python Lambda function?🐾
There are several ways to write logs from Python Lambda function to AWS CloudWatch:
1️⃣ print(”Yay, done!”)
Print statements are logged to CLoudWatch only when invoked in AWS console. This method is valid only for development or debugging. In case you want your production workload to log all print statement, you need to redirect standard output to the standard error stream by using sys.stdout = sys.stderr in the application code.
2️⃣ context.log(”Yay, done!”)
Lambda context provides built-in logging functionality without any additional installations or imports. On the other hand, it does not provide any logs customization. So it's a simple and the most straightforward way to log information from your Lambda function.
3️⃣ import logging; logging.info(”Yay, done!”)
Python’s logging library offers a range of features and customization options for your logs, including different logging levels, formats, and more. This method is suitable for scenarios where you have more advanced logging requirements.
4️⃣ from aws_lambda_powertools import Logger; Logger.info(”Yay, done!”)
Powertools for AWS Lambda ensures consistent log formatting across different Lambda functions within your application. It provides predefined log formatters that can be easily customized to suit your needs. It integrates with Lambda context and enriches your logs with contextual information such as function name, AWS Request ID, and trace IDs. To use Powertools, you need to add AWS-managed layer to your function.
Over to you: which logging method do you prefer for your Lambda functions? Share your thoughts in the comments below. 🤓
Documentation for AWS Powertools for Lambda.
If you like this post, you can share APAWS newsletter with friends: