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

Noisy exceptions - force logging of all exceptions #2262

Merged
merged 15 commits into from Oct 27, 2021
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions sanic/__main__.py
Expand Up @@ -96,6 +96,11 @@ def main():
help="number of worker processes [default 1]\n ",
)
parser.add_argument("-d", "--debug", dest="debug", action="store_true")
parser.add_argument(
"--noisy-exceptions",
dest="noisy_exceptions",
action="store_true",
)
parser.add_argument(
"-r",
"--reload",
Expand Down Expand Up @@ -149,6 +154,7 @@ def main():
f"Module is not a Sanic app, it is a {app_type_name}. "
f"Perhaps you meant {args.module}.app?"
)

if args.cert is not None or args.key is not None:
ssl: Optional[Dict[str, Any]] = {
"cert": args.cert,
Expand All @@ -165,6 +171,7 @@ def main():
"debug": args.debug,
"access_log": args.access_log,
"ssl": ssl,
"noisy_exceptions": args.noisy_exceptions,
}
if args.auto_reload:
kwargs["auto_reload"] = True
Expand Down
9 changes: 8 additions & 1 deletion sanic/app.py
Expand Up @@ -890,7 +890,8 @@ async def _websocket_handler(
try:
await fut
except Exception as e:
self.error_handler.log(request, e)
noisy = self.error_handler.noisy
self.error_handler._log(request, e, noisy)
prryplatypus marked this conversation as resolved.
Show resolved Hide resolved
except (CancelledError, ConnectionClosed):
cancelled = True
finally:
Expand Down Expand Up @@ -954,6 +955,7 @@ def run(
unix: Optional[str] = None,
loop: None = None,
reload_dir: Optional[Union[List[str], str]] = None,
noisy_exceptions: bool = False,
) -> None:
"""
Run the HTTP Server and listen until keyboard interrupt or term
Expand Down Expand Up @@ -1036,6 +1038,7 @@ def run(
backlog=backlog,
register_sys_signals=register_sys_signals,
auto_reload=auto_reload,
noisy_exceptions=noisy_exceptions,
)

try:
Expand Down Expand Up @@ -1082,6 +1085,7 @@ async def create_server(
unix: Optional[str] = None,
return_asyncio_server: bool = False,
asyncio_server_kwargs: Dict[str, Any] = None,
noisy_exceptions: bool = False,
) -> Optional[AsyncioServer]:
"""
Asynchronous version of :func:`run`.
Expand Down Expand Up @@ -1144,6 +1148,7 @@ async def create_server(
protocol=protocol,
backlog=backlog,
run_async=return_asyncio_server,
noisy_exceptions=noisy_exceptions,
)

main_start = server_settings.pop("main_start", None)
Expand Down Expand Up @@ -1256,6 +1261,7 @@ def _helper(
register_sys_signals=True,
run_async=False,
auto_reload=False,
noisy_exceptions=False,
):
"""Helper function used by `run` and `create_server`."""

Expand All @@ -1276,6 +1282,7 @@ def _helper(
)

self.error_handler.debug = debug
self.error_handler.noisy = noisy_exceptions
self.debug = debug

server_settings = {
Expand Down
30 changes: 27 additions & 3 deletions sanic/handlers.py
Expand Up @@ -34,6 +34,7 @@ def __init__(
Tuple[Type[BaseException], Optional[str]], Optional[RouteHandler]
] = {}
self.debug = False
self.noisy = False
self.fallback = fallback
self.base = base

Expand All @@ -59,6 +60,21 @@ def finalize(cls, error_handler):
)
error_handler._lookup = error_handler._legacy_lookup

sig = signature(error_handler.log)
if len(sig.parameters) == 2:
error_logger.warning(
DeprecationWarning(
"You are using a deprecated error handler. The log "
"method should accept three positional parameters: "
"(request, exception, noisy: bool). "
"Until you upgrade your ErrorHandler.log, the noisy "
"exceptions setting will not work properly. Beginning "
"in v??.?, the legacy style log method will not "
"work at all."
),
)
error_handler._log = error_handler._legacy_log

def _full_lookup(self, exception, route_name: Optional[str] = None):
return self.lookup(exception, route_name)

Expand Down Expand Up @@ -180,7 +196,7 @@ def default(self, request, exception):
:class:`Exception`
:return:
"""
self.log(request, exception)
self._log(request, exception, self.noisy)
return exception_response(
request,
exception,
Expand All @@ -189,10 +205,16 @@ def default(self, request, exception):
fallback=self.fallback,
)

def _full_log(self, request, exception, noisy: bool):
self.log(request, exception, noisy)

def _legacy_log(self, request, exception, noisy: bool):
self.log(request, exception) # type: ignore

@staticmethod
def log(request, exception):
def log(request, exception, noisy: bool):
quiet = getattr(exception, "quiet", False)
if quiet is False:
if quiet is False or noisy is True:
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
try:
url = repr(request.url)
except AttributeError:
Expand All @@ -202,6 +224,8 @@ def log(request, exception):
"Exception occurred while handling uri: %s", url
)

_log = _full_log


class ContentRangeHandler:
"""
Expand Down
43 changes: 43 additions & 0 deletions tests/test_exceptions_handler.py
Expand Up @@ -227,3 +227,46 @@ def lookup(self, exception):
"v22.3, the legacy style lookup method will not work at all."
)
assert response.status == 400


def test_double_arg_exception_handler_log_notice(exception_handler_app, caplog):
class CustomErrorHandler(ErrorHandler):
@staticmethod
def log(request, exception):
pass

exception_handler_app.error_handler = CustomErrorHandler()

with caplog.at_level(logging.WARNING):
_, response = exception_handler_app.test_client.get("/1")

assert caplog.records[0].message == (
"You are using a deprecated error handler. The log "
"method should accept three positional parameters: "
"(request, exception, noisy: bool). "
"Until you upgrade your ErrorHandler.log, the noisy "
"exceptions setting will not work properly. Beginning "
"in v??.?, the legacy style log method will not "
"work at all."
)
assert response.status == 400


def test_error_handler_noisy_log(caplog):
class CustomError(Exception):
quiet = True

class FakeRequest(object):
url = "http://127.0.0.1:8000"

with caplog.at_level(logging.ERROR):
ErrorHandler.log(FakeRequest(), CustomError(), False)

assert len(caplog.records) == 0

with caplog.at_level(logging.ERROR):
ErrorHandler.log(FakeRequest(), CustomError(), True)

assert caplog.records[0].message == (
"Exception occurred while handling uri: '%s'" % FakeRequest.url
)