Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce access log overhead when logging is disabled #7240

Merged
merged 11 commits into from
Apr 16, 2023
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/7240.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Turned access log into no-op when the logger is disabled.
3 changes: 3 additions & 0 deletions aiohttp/web_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
bdraco marked this conversation as resolved.
Show resolved Hide resolved
# Avoid formatting the log line if it will not be emitted.
return
try:
fmt_info = self._format_line(request, response, time)

Expand Down
18 changes: 18 additions & 0 deletions tests/test_web_log.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# type: ignore
import datetime
import logging
import platform
import sys
from typing import Any
Expand Down Expand Up @@ -251,3 +252,20 @@ 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:
Dreamsorcerer marked this conversation as resolved.
Show resolved Hide resolved
"""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
caplog.clear()
mock_logger.setLevel(logging.WARNING)
access_logger.log(
mock.Mock(name="mock_request"), mock.Mock(name="mock_response"), 42
)
assert "mock_response" not in caplog.text
Dreamsorcerer marked this conversation as resolved.
Show resolved Hide resolved