From 1f89763e1825eb6b3bb9986b5bc00aa09e99c5ef Mon Sep 17 00:00:00 2001 From: Amin Alaee Date: Sun, 13 Feb 2022 12:32:47 +0100 Subject: [PATCH] :speech_balloon: Improve logging (#230) * Improve logging --- mangum/protocols/http.py | 9 ++++++--- tests/test_http.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/mangum/protocols/http.py b/mangum/protocols/http.py index 7e82d017..33db249e 100644 --- a/mangum/protocols/http.py +++ b/mangum/protocols/http.py @@ -108,9 +108,6 @@ async def send(self, message: Message) -> None: Awaited by the application to send ASGI `http` events. """ message_type = message["type"] - self.logger.info( - "%s: '%s' event received from application.", self.state, message_type - ) if ( self.state is HTTPCycleState.REQUEST @@ -141,6 +138,12 @@ async def send(self, message: Message) -> None: self.state = HTTPCycleState.COMPLETE await self.app_queue.put({"type": "http.disconnect"}) + self.logger.info( + "%s %s %s", + self.request.method, + self.request.path, + self.response.status, + ) else: raise UnexpectedMessage( f"{self.state}: Unexpected '{message_type}' event received." diff --git a/tests/test_http.py b/tests/test_http.py index b45ae518..825b630e 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -603,3 +603,33 @@ async def app(scope, receive, send): "vary": "Accept-Encoding", } assert response["body"] == base64.b64encode(brotli.compress(body.encode())).decode() + + +@pytest.mark.parametrize( + "mock_aws_api_gateway_event", [["GET", b"", None]], indirect=True +) +def test_http_logging(mock_aws_api_gateway_event, caplog) -> None: + async def app(scope, receive, send): + assert scope["type"] == "http" + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [[b"content-type", b"text/plain; charset=utf-8"]], + } + ) + + await send({"type": "http.response.body", "body": b"Hello, world!"}) + + handler = Mangum(app, lifespan="off") + response = handler(mock_aws_api_gateway_event, {}) + + assert response == { + "statusCode": 200, + "isBase64Encoded": False, + "headers": {"content-type": "text/plain; charset=utf-8"}, + "multiValueHeaders": {}, + "body": "Hello, world!", + } + + assert "GET /test/hello 200" in caplog.text