Last active
January 4, 2021 19:20
-
-
Save rgpower/c1ac232cf299eaa80c7829bdf51a1b39 to your computer and use it in GitHub Desktop.
Include RequestId in AWS Lambda CloudWatch logs
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
""" | |
Use this to get output that includes the Lambda context RequestId in your CloudWatch logs | |
This allows you to differentiate the logs of concurrent invocations. | |
To use in your lambda: | |
import logging | |
logging.getLogger().setLevel(logging.INFO) | |
def handler(event, context): | |
RequestIdLoggerFilter.install(context) | |
logger.info("handler invoked") | |
""" | |
class RequestIdLoggerFilter(logging.Filter): | |
def __init__(self, request_id): | |
super().__init__() | |
self.request_id = request_id | |
fmt = " ".join( | |
[ | |
"%(levelname)s RequestId: %(aws_request_id)s %(asctime)s.%(msecs)03dZ", | |
"[%(filename)s:%(lineno)d %(funcName)10s] %(message)s\n", | |
] | |
) | |
self.formatter = logging.Formatter(fmt, "%Y-%m-%dT%H:%M:%S") | |
def filter(self, record): | |
record.aws_request_id = self.request_id | |
return True | |
@classmethod | |
def install(cls, lambda_context): | |
self = cls(lambda_context.aws_request_id) | |
for h in logging.getLogger().handlers: | |
h.setFormatter(self.formatter) | |
h.addFilter(self) | |
return self |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment