diff --git a/CHANGES/7240.feature b/CHANGES/7240.feature new file mode 100644 index 00000000000..e656f1369f6 --- /dev/null +++ b/CHANGES/7240.feature @@ -0,0 +1 @@ +Turned access log into no-op when the logger is disabled. diff --git a/aiohttp/web_log.py b/aiohttp/web_log.py index 0fd862e6a84..633e9e3ae6b 100644 --- a/aiohttp/web_log.py +++ b/aiohttp/web_log.py @@ -189,6 +189,9 @@ def _format_line( return [(key, method(request, response, time)) for key, method in self._methods] def log(self, request: BaseRequest, response: StreamResponse, time: float) -> None: + if not self.logger.isEnabledFor(logging.INFO): + # Avoid formatting the log line if it will not be emitted. + return try: fmt_info = self._format_line(request, response, time) diff --git a/tests/test_web_log.py b/tests/test_web_log.py index fa5fb27f744..6a09479f4b7 100644 --- a/tests/test_web_log.py +++ b/tests/test_web_log.py @@ -1,5 +1,6 @@ # type: ignore import datetime +import logging import platform import sys from typing import Any @@ -251,3 +252,14 @@ def log(self, request, response, time): resp = await client.get("/") assert 200 == resp.status assert msg == "contextvars: uuid" + + +def test_logger_does_nothing_when_disabled(caplog: pytest.LogCaptureFixture) -> None: + """Test that the logger does nothing when the log level is disabled.""" + mock_logger = logging.getLogger("test.aiohttp.log") + mock_logger.setLevel(logging.INFO) + access_logger = AccessLogger(mock_logger, "%b") + access_logger.log( + mock.Mock(name="mock_request"), mock.Mock(name="mock_response"), 42 + ) + assert "mock_response" in caplog.text