Skip to content

Commit

Permalink
Fix: Log request body (#6404)
Browse files Browse the repository at this point in the history
  • Loading branch information
achave11-ucsc committed Aug 31, 2024
1 parent ec4e3b1 commit 6fc7975
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/azul/chalice.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
json_head,
)
from azul.types import (
AnyJSON,
JSON,
LambdaContext,
MutableJSON,
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit 6fc7975

Please sign in to comment.