From 6fc79757c3b950e7b9e83de3d63792ef7f31b256 Mon Sep 17 00:00:00 2001 From: Abraham Chavez Date: Fri, 30 Aug 2024 18:06:12 -0700 Subject: [PATCH] Fix: Log request body (#6404) --- src/azul/chalice.py | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/src/azul/chalice.py b/src/azul/chalice.py index f7ad22b12..1291eeea2 100644 --- a/src/azul/chalice.py +++ b/src/azul/chalice.py @@ -62,6 +62,7 @@ json_head, ) from azul.types import ( + AnyJSON, JSON, LambdaContext, MutableJSON, @@ -382,18 +383,34 @@ def _log_request(self): 'query': self.current_request.query_params, 'headers': self.current_request.headers } - log.info('Received %s request for %r, with %s.', + log.info('Received %s request for %r, with %s', context['httpMethod'], context['path'], json.dumps(request_info, cls=self._LogJSONEncoder)) + body = self.current_request.raw_body.decode() + size = len(body) + if config.debug > 1: + log_ = log.debug + else: + body = '(first 1024 chars) ' + self.__get_first_n_chars(1024, body) + log_ = log.info + log_('… with request body %s, of size %i.', body, size) + + def __get_first_n_chars(self, n: int, body: str | AnyJSON) -> str: + """ + Used by the logger to shorten the body from requests or responses. This + is done so that only the first n characters of the provided body are + logged, useful for non-comprehensive logging levels. + """ + if isinstance(body, str): + body = body[:n] + else: + body = json_head(n, body) + return body def _log_response(self, response): if log.isEnabledFor(logging.DEBUG): - n = 1024 - if isinstance(response.body, str): - body = response.body[:n] - else: - body = json_head(n, response.body) + body = self.__get_first_n_chars(n := 1024, response.body) log.debug('Returning %i response with headers %s. ' 'See next line for the first %i characters of the body.\n%s', response.status_code,