From 53a571ec6c49a328f5920604d3dbfa38df57ee07 Mon Sep 17 00:00:00 2001 From: ENT8R Date: Sat, 10 Apr 2021 20:35:53 +0200 Subject: [PATCH] Consistent use of error loggers (#2109) * Consistent use of error loggers * Fix tests --- sanic/__main__.py | 6 +++--- sanic/handlers.py | 8 +++++--- sanic/http.py | 4 ++-- sanic/server.py | 18 +++++++++--------- tests/test_app.py | 2 +- tests/test_logging.py | 6 +++--- tests/test_middleware.py | 4 ++-- 7 files changed, 25 insertions(+), 23 deletions(-) diff --git a/sanic/__main__.py b/sanic/__main__.py index 6619705c..43836bfb 100644 --- a/sanic/__main__.py +++ b/sanic/__main__.py @@ -8,7 +8,7 @@ from typing import Any, Dict, Optional from sanic import __version__ from sanic.app import Sanic from sanic.config import BASE_LOGO -from sanic.log import logger +from sanic.log import error_logger class SanicArgumentParser(ArgumentParser): @@ -119,13 +119,13 @@ def main(): ssl=ssl, ) except ImportError as e: - logger.error( + error_logger.error( f"No module named {e.name} found.\n" f" Example File: project/sanic_server.py -> app\n" f" Example Module: project.sanic_server.app" ) except ValueError: - logger.exception("Failed to run app") + error_logger.exception("Failed to run app") if __name__ == "__main__": diff --git a/sanic/handlers.py b/sanic/handlers.py index 2f15c143..dc6c7bea 100644 --- a/sanic/handlers.py +++ b/sanic/handlers.py @@ -6,7 +6,7 @@ from sanic.exceptions import ( HeaderNotFound, InvalidRangeType, ) -from sanic.log import logger +from sanic.log import error_logger from sanic.response import text @@ -101,7 +101,7 @@ class ErrorHandler: response_message = ( "Exception raised in exception handler " '"%s" for uri: %s' ) - logger.exception(response_message, handler.__name__, url) + error_logger.exception(response_message, handler.__name__, url) if self.debug: return text(response_message % (handler.__name__, url), 500) @@ -137,7 +137,9 @@ class ErrorHandler: url = "unknown" self.log(format_exc()) - logger.exception("Exception occurred while handling uri: %s", url) + error_logger.exception( + "Exception occurred while handling uri: %s", url + ) return exception_response(request, exception, self.debug) diff --git a/sanic/http.py b/sanic/http.py index 3dcfb22c..19ed89d3 100644 --- a/sanic/http.py +++ b/sanic/http.py @@ -20,7 +20,7 @@ from sanic.exceptions import ( ) from sanic.headers import format_http1_response from sanic.helpers import has_message_body -from sanic.log import access_logger, logger +from sanic.log import access_logger, error_logger, logger class Stage(Enum): @@ -143,7 +143,7 @@ class Http: # Try to consume any remaining request body if self.request_body: if self.response and 200 <= self.response.status < 300: - logger.error(f"{self.request} body not consumed.") + error_logger.error(f"{self.request} body not consumed.") try: async for _ in self: diff --git a/sanic/server.py b/sanic/server.py index 88013d44..0d88259a 100644 --- a/sanic/server.py +++ b/sanic/server.py @@ -39,7 +39,7 @@ from sanic.compat import OS_IS_WINDOWS, ctrlc_workaround_for_windows from sanic.config import Config from sanic.exceptions import RequestTimeout, ServiceUnavailable from sanic.http import Http, Stage -from sanic.log import logger +from sanic.log import error_logger, logger from sanic.models.protocol_types import TransportProtocol from sanic.request import Request @@ -199,11 +199,11 @@ class HttpProtocol(asyncio.Protocol): except CancelledError: pass except Exception: - logger.exception("protocol.connection_task uncaught") + error_logger.exception("protocol.connection_task uncaught") finally: if self.app.debug and self._http: ip = self.transport.get_extra_info("peername") - logger.error( + error_logger.error( "Connection lost before response written" f" @ {ip} {self._http.request}" ) @@ -212,7 +212,7 @@ class HttpProtocol(asyncio.Protocol): try: self.close() except BaseException: - logger.exception("Closing failed") + error_logger.exception("Closing failed") async def receive_more(self): """ @@ -258,7 +258,7 @@ class HttpProtocol(asyncio.Protocol): return self._task.cancel() except Exception: - logger.exception("protocol.check_timeouts") + error_logger.exception("protocol.check_timeouts") async def send(self, data): """ @@ -304,7 +304,7 @@ class HttpProtocol(asyncio.Protocol): self.recv_buffer = bytearray() self.conn_info = ConnInfo(self.transport, unix=self._unix) except Exception: - logger.exception("protocol.connect_made") + error_logger.exception("protocol.connect_made") def connection_lost(self, exc): try: @@ -313,7 +313,7 @@ class HttpProtocol(asyncio.Protocol): if self._task: self._task.cancel() except Exception: - logger.exception("protocol.connection_lost") + error_logger.exception("protocol.connection_lost") def pause_writing(self): self._can_write.clear() @@ -337,7 +337,7 @@ class HttpProtocol(asyncio.Protocol): if self._data_received: self._data_received.set() except Exception: - logger.exception("protocol.data_received") + error_logger.exception("protocol.data_received") def trigger_events(events: Optional[Iterable[Callable[..., Any]]], loop): @@ -556,7 +556,7 @@ def serve( try: http_server = loop.run_until_complete(server_coroutine) except BaseException: - logger.exception("Unable to start server") + error_logger.exception("Unable to start server") return trigger_events(after_start, loop) diff --git a/tests/test_app.py b/tests/test_app.py index f096496a..9acdb0cd 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -276,7 +276,7 @@ def test_handle_request_with_nested_sanic_exception(app, monkeypatch, caplog): assert response.status == 500 assert "Mock SanicException" in response.text assert ( - "sanic.root", + "sanic.error", logging.ERROR, f"Exception occurred while handling uri: 'http://127.0.0.1:{port}/'", ) in caplog.record_tuples diff --git a/tests/test_logging.py b/tests/test_logging.py index 0e467a10..5f531670 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -113,9 +113,9 @@ def test_logging_pass_customer_logconfig(): def test_log_connection_lost(app, debug, monkeypatch): """ Should not log Connection lost exception on non debug """ stream = StringIO() - root = logging.getLogger("sanic.root") - root.addHandler(logging.StreamHandler(stream)) - monkeypatch.setattr(sanic.server, "logger", root) + error = logging.getLogger("sanic.error") + error.addHandler(logging.StreamHandler(stream)) + monkeypatch.setattr(sanic.server, "error_logger", error) @app.route("/conn_lost") async def conn_lost(request): diff --git a/tests/test_middleware.py b/tests/test_middleware.py index a6c893b4..cc7edae2 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -156,7 +156,7 @@ def test_middleware_response_raise_cancelled_error(app, caplog): assert response.status == 503 assert ( - "sanic.root", + "sanic.error", logging.ERROR, "Exception occurred while handling uri: 'http://127.0.0.1:42101/'", ) not in caplog.record_tuples @@ -174,7 +174,7 @@ def test_middleware_response_raise_exception(app, caplog): assert response.status == 404 # 404 errors are not logged assert ( - "sanic.root", + "sanic.error", logging.ERROR, "Exception occurred while handling uri: 'http://127.0.0.1:42101/'", ) not in caplog.record_tuples