I am working on a Lambda FAAS and I am trying to debug by writing data to the "log" which happens to be the CloudTrail Log Stream.

In nodejs, I can simply put the following in my Lambda FAAS and I can see it in my CloudTrail Log Stream for that particular call:

log('this will be written in cloudtrail log stream')

How would I do the following in Python 3 inside Lambda? Any help would be greatly appreciated.

3 Answers

1
HollerTrain On

import logging

in the code add:

logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
1
Nagendra Kakarla On

You can use the logging module or just use print statements. AWS documentation explains it in detail with examples

https://docs.aws.amazon.com/lambda/latest/dg/python-logging.html

from __future__ import print_function

def lambda_handler(event, context):
    print('this will also show up in cloud watch')

  return 'Hello World!'

0
Joseph On

AWS automatically picks up any messages sent to the log or to std out (print statements) and pushes them to cloudWach as long as the role configured in the lambda function has accesses to write to the cloud watch logs. Lambda Assumes this role and uses the permissions policies to gain access to CloudWatch Logs to write the logs.

You will need a policy attached to the role like the following, or you can attach the AWS Policy called "AWSLambdaBasicExecutionRole" :

                     {
                            "Version": "2012-10-17",
                            "Statement": [
                              {
                                "Effect": "Allow",
                                "Action": [
                                  "logs:CreateLogGroup",
                                  "logs:CreateLogStream",
                                  "logs:PutLogEvents",
                                  "logs:DescribeLogStreams"
                              ],
                                "Resource": [
                                  "arn:aws:logs:*:*:*"
                              ]
                            }
                           ]
                        }

Without the correct permissions, you will see the error in CloudWatch "There was an error loading log streams. Please try again by refreshing this page."

This Video will demonstrate the the permissions issue as well as viewing the logs in cloud watch. https://studio.youtube.com/video/0VPTlPSfFiE/edit

References: https://geektopia.tech/post.php?blogpost=Write_To_CloudWatch_Logs_From_Lambda https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions.html