Add ability to log all exceptions (#2262)

* Add ability to log all exceptions

* Fix linting 🙄

* Remove shorthand

* Make `ErrorHandler.log` backwards-compat

* Ignore mypy error

* Don't store `noisy_exceptions` attribute in app

* Added tests

* Store noisy exceptions setting in config

* Default to not-noisy if config key not available

* Add CLI tests for `noisy-exceptions`

* Remove debugging line I left in 😅

* Fix tests

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
This commit is contained in:
Néstor Pérez
2021-10-27 09:43:58 +02:00
committed by GitHub
parent 71cc30e5cd
commit f0f81ec458
7 changed files with 63 additions and 2 deletions

View File

@@ -23,6 +23,7 @@ async def app_info_dump(app: Sanic, _):
"access_log": app.config.ACCESS_LOG,
"auto_reload": app.auto_reload,
"debug": app.debug,
"noisy_exceptions": app.config.NOISY_EXCEPTIONS,
}
logger.info(json.dumps(app_data))

View File

@@ -182,3 +182,21 @@ def test_version(cmd):
version_string = f"Sanic {__version__}; Routing {__routing_version__}\n"
assert out == version_string.encode("utf-8")
@pytest.mark.parametrize(
"cmd,expected",
(
("--noisy-exceptions", True),
("--no-noisy-exceptions", False),
),
)
def test_noisy_exceptions(cmd, expected):
command = ["sanic", "fake.server.app", cmd]
out, err, exitcode = capture(command)
lines = out.split(b"\n")
app_info = lines[26]
info = json.loads(app_info)
assert info["noisy_exceptions"] is expected

View File

@@ -2,10 +2,11 @@ import asyncio
import logging
import pytest
from unittest.mock import Mock
from bs4 import BeautifulSoup
from sanic import Sanic
from sanic import Sanic, handlers
from sanic.exceptions import Forbidden, InvalidUsage, NotFound, ServerError
from sanic.handlers import ErrorHandler
from sanic.response import stream, text
@@ -227,3 +228,18 @@ def test_single_arg_exception_handler_notice(exception_handler_app, caplog):
"v22.3, the legacy style lookup method will not work at all."
)
assert response.status == 400
def test_error_handler_noisy_log(exception_handler_app, monkeypatch):
err_logger = Mock()
monkeypatch.setattr(handlers, "error_logger", err_logger)
exception_handler_app.config["NOISY_EXCEPTIONS"] = False
exception_handler_app.test_client.get("/1")
err_logger.exception.assert_not_called()
exception_handler_app.config["NOISY_EXCEPTIONS"] = True
request, _ = exception_handler_app.test_client.get("/1")
err_logger.exception.assert_called_with(
"Exception occurred while handling uri: %s", repr(request.url)
)