Configure logging in AWS Lambda to CloudWatch using Python

Logging events to CloudWatch log stream during execution is as simple as normal logging. You might be tempted to use print, and it may work, if it's not a good practice.

Rather you should be using the logging module.

Below in a rather simple example, I write a Lambda function that logs a "Hello, today is <today's date>!" message to CloudWatch log stream.

Getting Started

You should follow the steps in this SAM guide to setup a basic Lambda function to setup a Lambda function.

Writing a Lambda function to log to CloudWatch

Edit the Lambda function under hellow_world/, and change the code to the following

import logging
from datetime import datetime

logger = logging.getLogger("HELLO")

date_today ="%Y-%m-%d")

def lambda_handler(event, context):"Hello, today is {date_today}!")

Then execute this by following the instructions here instructions here.

Now you can go to the Lambda function's CloudWatch log stream and see the message being printed everytime you execute the funcion.

Need Help? Open a discussion thread on GitHub.

Related Posts