Forked from gene1wood/log_aws_lambda_event_and_context.py
Created
October 13, 2018 00:38
-
-
Save progvp/34c811f40813865fb7ffa251a0030a96 to your computer and use it in GitHub Desktop.
A python AWS Lambda function which logs the contents of the event and context variables passed into the function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import json | |
logger = logging.getLogger(__name__) | |
logging.getLogger().setLevel(logging.INFO) | |
class PythonObjectEncoder(json.JSONEncoder): | |
"""Custom JSON Encoder that allows encoding of un-serializable objects | |
For object types which the json module cannot natively serialize, if the | |
object type has a __repr__ method, serialize that string instead. | |
Usage: | |
>>> example_unserializable_object = {'example': set([1,2,3])} | |
>>> print(json.dumps(example_unserializable_object, | |
cls=PythonObjectEncoder)) | |
{"example": "set([1, 2, 3])"} | |
""" | |
def default(self, obj): | |
if isinstance(obj, | |
(list, dict, str, unicode, | |
int, float, bool, type(None))): | |
return json.JSONEncoder.default(self, obj) | |
elif hasattr(obj, '__repr__'): | |
return obj.__repr__() | |
else: | |
return json.JSONEncoder.default(self, obj.__repr__()) | |
def lambda_handler(event, context): | |
logger.info('Event: %s' % json.dumps(event)) | |
logger.info('Context: %s' % | |
json.dumps(vars(context), cls=PythonObjectEncoder)) | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment