Last active
April 12, 2023 10:16
-
-
Save saswata-dutta/6e883a02e0e24015201b85b6bea371da to your computer and use it in GitHub Desktop.
AWS Lambda handler to avoid splitting log lines in cloudwatch
This file contains hidden or 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 sys | |
import logging | |
import traceback | |
import json | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
def process(record): | |
logger.info(record["x"]) | |
# TODO | |
def log_exception(mssg): | |
ex_type, ex_value, ex_tb = sys.exc_info() | |
tb_str = traceback.format_exception(ex_type, ex_value, ex_tb) | |
err_details = json.dumps( | |
{ | |
"level": "ERROR", | |
"message": mssg, | |
"exception_type": ex_type.__name__, | |
"exception_message": str(ex_value), | |
"stack_trace": tb_str, | |
} | |
) | |
logger.error(err_details) | |
def lambda_handler(event, context): | |
"""handles SQS message batch""" | |
if event: | |
logger.info(f"event: {event}") | |
batch_item_failures = [] | |
sqs_batch_response = {} | |
for record in event["Records"]: | |
try: | |
process(record) | |
except Exception: | |
batch_item_failures.append({"itemIdentifier": record["messageId"]}) | |
log_exception(f"Failed processing {record}") | |
sqs_batch_response["batchItemFailures"] = batch_item_failures | |
return sqs_batch_response | |
lambda_handler( | |
{ | |
"Records": [ | |
{"messageId": 1, "x": 1}, | |
{"messageId": 2, "y": 1}, | |
{"messageId": 3, "z": 1}, | |
] | |
}, | |
None, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment