Skip to content

Commit 21f4a2f

Browse files
JacobCoffeecofinGoldziherprovinzkrautpeterschutt
authored
(958) Add exception logging in debug mode (#976)
* feat: add console output for exceptions in debug mode * chore: middleware debug logging updates * feat: #958 testing passing * Update starlite/middleware/exceptions/middleware.py Co-authored-by: Na'aman Hirschfeld <[email protected]> * chore: fixed test for middleware debug logging (#958) * Update tests/middleware/test_exception_handler_middleware.py * chore: fixed test for middleware debug logging (#958) * Use `get_logger` fixture to test exception logged in debug. - moves get_logger fixture to conftest.py for middleware tests - patches app logger in tests with one that propagates so caplog works. * chore: Updated assertions (#958) * Update starlite/middleware/exceptions/middleware.py Co-authored-by: Na'aman Hirschfeld <[email protected]> * chore: update logger method --------- Co-authored-by: Jacob Coffee <[email protected]> Co-authored-by: Cody Fincher <[email protected]> Co-authored-by: Na'aman Hirschfeld <[email protected]> Co-authored-by: provinzkraut <[email protected]> Co-authored-by: Peter Schutt <[email protected]> Co-authored-by: Peter Schutt <[email protected]> Co-authored-by: Peter Schutt <[email protected]>
1 parent 354942e commit 21f4a2f

File tree

4 files changed

+68
-15
lines changed

4 files changed

+68
-15
lines changed

starlite/middleware/exceptions/middleware.py

+2
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> No
4747
await self.app(scope, receive, send)
4848
except Exception as e: # pylint: disable=broad-except
4949
starlite_app = scope["app"]
50+
if self.debug and (logger := starlite_app.get_logger()):
51+
logger.debug("exception raised for request to route %s", scope["path"], exc_info=True)
5052
for hook in starlite_app.after_exception:
5153
await hook(e, scope, starlite_app.state)
5254

tests/middleware/conftest.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from typing import TYPE_CHECKING
2+
3+
import pytest
4+
5+
from starlite.config.logging import LoggingConfig, default_handlers
6+
7+
if TYPE_CHECKING:
8+
from starlite.types.callable_types import GetLogger
9+
10+
11+
@pytest.fixture
12+
def get_logger() -> "GetLogger":
13+
# due to the limitations of caplog we have to place this call here.
14+
# we also have to allow propagation.
15+
return LoggingConfig(
16+
handlers=default_handlers,
17+
loggers={
18+
"starlite": {"level": "DEBUG", "handlers": ["queue_listener"], "propagate": True},
19+
},
20+
).configure()

tests/middleware/test_exception_handler_middleware.py

+46-2
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,28 @@
11
import json
2-
from typing import TYPE_CHECKING, Any
2+
from typing import TYPE_CHECKING, Any, Optional
33

4+
import pytest
45
from starlette.exceptions import HTTPException as StarletteHTTPException
56

6-
from starlite import HTTPException, Request, Response, Starlite, get
7+
from starlite import (
8+
HTTPException,
9+
LoggingConfig,
10+
Request,
11+
Response,
12+
Starlite,
13+
TestClient,
14+
get,
15+
)
716
from starlite.middleware.exceptions import ExceptionHandlerMiddleware
817
from starlite.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
918
from starlite.testing import create_test_client
1019

1120
if TYPE_CHECKING:
21+
from _pytest.logging import LogCaptureFixture
22+
1223
from starlite.datastructures import State
1324
from starlite.types import Scope
25+
from starlite.types.callable_types import GetLogger
1426

1527

1628
async def dummy_app(scope: Any, receive: Any, send: Any) -> None:
@@ -118,3 +130,35 @@ async def after_exception_hook_handler(exc: Exception, scope: "Scope", state: "S
118130
response = client.get("/test")
119131
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
120132
assert client.app.state.called
133+
134+
135+
@pytest.mark.parametrize(
136+
"debug,logging_config",
137+
[
138+
(True, LoggingConfig()),
139+
(False, LoggingConfig()),
140+
(False, None),
141+
],
142+
)
143+
def test_exception_handler_middleware_debug_logging(
144+
get_logger: "GetLogger", caplog: "LogCaptureFixture", debug: bool, logging_config: Optional[LoggingConfig]
145+
) -> None:
146+
@get("/test")
147+
def handler() -> None:
148+
raise ValueError("Test debug exception")
149+
150+
app = Starlite([handler], logging_config=logging_config, debug=debug)
151+
152+
with caplog.at_level("DEBUG", "starlite"), TestClient(app=app) as client:
153+
client.app.logger = get_logger("starlite")
154+
response = client.get("/test")
155+
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
156+
assert "Test debug exception" in response.text
157+
158+
if debug and logging_config:
159+
assert len(caplog.records) == 1
160+
assert caplog.records[0].levelname == "DEBUG"
161+
assert "exception raised for request to route" in caplog.records[0].message
162+
else:
163+
assert not caplog.records
164+
assert "exception raised for request to route" not in response.text

tests/middleware/test_logging_middleware.py

-13
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
from starlite import Cookie, LoggingConfig, Response, StructLoggingConfig, get, post
88
from starlite.config.compression import CompressionConfig
9-
from starlite.config.logging import default_handlers
109
from starlite.middleware import LoggingMiddlewareConfig
1110
from starlite.status_codes import HTTP_200_OK
1211
from starlite.testing import create_test_client
@@ -26,18 +25,6 @@ def handler() -> Response:
2625
)
2726

2827

29-
@pytest.fixture
30-
def get_logger() -> "GetLogger":
31-
# due to the limitations of caplog we have to place this call here.
32-
# we also have to allow propagation.
33-
return LoggingConfig(
34-
handlers=default_handlers,
35-
loggers={
36-
"starlite": {"level": "INFO", "handlers": ["queue_listener"], "propagate": True},
37-
},
38-
).configure()
39-
40-
4128
def test_logging_middleware_regular_logger(get_logger: "GetLogger", caplog: "LogCaptureFixture") -> None:
4229
with create_test_client(
4330
route_handlers=[handler], middleware=[LoggingMiddlewareConfig().middleware]

0 commit comments

Comments
 (0)