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

(958) Add exception logging in debug mode #976

Merged
merged 19 commits into from
Feb 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
5320752
feat: add console output for exceptions in debug mode
JacobCoffee Dec 22, 2022
5f0a127
Merge branch 'main' into 985_debug_console_log_enhancements
JacobCoffee Jan 8, 2023
0f19be7
chore: middleware debug logging updates
JacobCoffee Jan 21, 2023
5105bd2
Merge branch 'main' into 985_debug_console_log_enhancements
cofin Jan 23, 2023
ad951a3
feat: #958 testing passing
JacobCoffee Jan 23, 2023
998c4cd
Update starlite/middleware/exceptions/middleware.py
JacobCoffee Jan 24, 2023
fd3c4be
Merge branch 'main' into 985_debug_console_log_enhancements
JacobCoffee Jan 27, 2023
5f37e99
chore: fixed test for middleware debug logging (#958)
JacobCoffee Jan 27, 2023
bac6a18
Update tests/middleware/test_exception_handler_middleware.py
provinzkraut Jan 31, 2023
de75bdf
Merge branch 'main' into 985_debug_console_log_enhancements
JacobCoffee Jan 31, 2023
e42d927
chore: fixed test for middleware debug logging (#958)
JacobCoffee Feb 1, 2023
faf06a1
Merge branch 'main' into 985_debug_console_log_enhancements
peterschutt Feb 3, 2023
dc74af2
Use `get_logger` fixture to test exception logged in debug.
peterschutt Feb 3, 2023
7a173e7
Merge pull request #4 from peterschutt/985_debug_console_log_enhancem…
JacobCoffee Feb 3, 2023
a65bfbc
Merge branch 'main' into 985_debug_console_log_enhancements
JacobCoffee Feb 3, 2023
9bc01e6
chore: Updated assertions (#958)
JacobCoffee Feb 3, 2023
8a0d0ed
Update starlite/middleware/exceptions/middleware.py
JacobCoffee Feb 3, 2023
dffccbf
chore: update logger method
JacobCoffee Feb 3, 2023
bde38f2
Merge branch 'main' into 985_debug_console_log_enhancements
JacobCoffee Feb 4, 2023
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
2 changes: 2 additions & 0 deletions starlite/middleware/exceptions/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> No
await self.app(scope, receive, send)
except Exception as e: # pylint: disable=broad-except
starlite_app = scope["app"]
if self.debug and (logger := starlite_app.get_logger()):
logger.debug("exception raised for request to route %s", scope["path"], exc_info=True)
for hook in starlite_app.after_exception:
await hook(e, scope, starlite_app.state)

Expand Down
20 changes: 20 additions & 0 deletions tests/middleware/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from typing import TYPE_CHECKING

import pytest

from starlite.config.logging import LoggingConfig, default_handlers

if TYPE_CHECKING:
from starlite.types.callable_types import GetLogger


@pytest.fixture
def get_logger() -> "GetLogger":
# due to the limitations of caplog we have to place this call here.
# we also have to allow propagation.
return LoggingConfig(
handlers=default_handlers,
loggers={
"starlite": {"level": "DEBUG", "handlers": ["queue_listener"], "propagate": True},
},
).configure()
48 changes: 46 additions & 2 deletions tests/middleware/test_exception_handler_middleware.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,28 @@
import json
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Optional

import pytest
from starlette.exceptions import HTTPException as StarletteHTTPException

from starlite import HTTPException, Request, Response, Starlite, get
from starlite import (
HTTPException,
LoggingConfig,
Request,
Response,
Starlite,
TestClient,
get,
)
from starlite.middleware.exceptions import ExceptionHandlerMiddleware
from starlite.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
from starlite.testing import create_test_client

if TYPE_CHECKING:
from _pytest.logging import LogCaptureFixture

from starlite.datastructures import State
from starlite.types import Scope
from starlite.types.callable_types import GetLogger


async def dummy_app(scope: Any, receive: Any, send: Any) -> None:
Expand Down Expand Up @@ -118,3 +130,35 @@ async def after_exception_hook_handler(exc: Exception, scope: "Scope", state: "S
response = client.get("/test")
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert client.app.state.called


@pytest.mark.parametrize(
"debug,logging_config",
[
(True, LoggingConfig()),
(False, LoggingConfig()),
(False, None),
],
)
def test_exception_handler_middleware_debug_logging(
get_logger: "GetLogger", caplog: "LogCaptureFixture", debug: bool, logging_config: Optional[LoggingConfig]
) -> None:
@get("/test")
def handler() -> None:
raise ValueError("Test debug exception")

app = Starlite([handler], logging_config=logging_config, debug=debug)

with caplog.at_level("DEBUG", "starlite"), TestClient(app=app) as client:
client.app.logger = get_logger("starlite")
response = client.get("/test")
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert "Test debug exception" in response.text

if debug and logging_config:
assert len(caplog.records) == 1
assert caplog.records[0].levelname == "DEBUG"
assert "exception raised for request to route" in caplog.records[0].message
else:
assert not caplog.records
assert "exception raised for request to route" not in response.text
13 changes: 0 additions & 13 deletions tests/middleware/test_logging_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

from starlite import Cookie, LoggingConfig, Response, StructLoggingConfig, get, post
from starlite.config.compression import CompressionConfig
from starlite.config.logging import default_handlers
from starlite.middleware import LoggingMiddlewareConfig
from starlite.status_codes import HTTP_200_OK
from starlite.testing import create_test_client
Expand All @@ -26,18 +25,6 @@ def handler() -> Response:
)


@pytest.fixture
def get_logger() -> "GetLogger":
# due to the limitations of caplog we have to place this call here.
# we also have to allow propagation.
return LoggingConfig(
handlers=default_handlers,
loggers={
"starlite": {"level": "INFO", "handlers": ["queue_listener"], "propagate": True},
},
).configure()


def test_logging_middleware_regular_logger(get_logger: "GetLogger", caplog: "LogCaptureFixture") -> None:
with create_test_client(
route_handlers=[handler], middleware=[LoggingMiddlewareConfig().middleware]
Expand Down