Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 7 additions & 7 deletions core/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,25 @@
add_log_level,
TimeStamper,
)
from structlog.dev import ConsoleRenderer
from structlog.dev import ConsoleRenderer, plain_traceback
import sys

from structlog.stdlib import LoggerFactory


def configure_structlog(is_production: bool = False):
shared_processors = [
base_processors = [
StackInfoRenderer(),
dict_tracebacks,
add_log_level,
TimeStamper(fmt="iso", utc=True),
]

if is_production:
processors = shared_processors + [JSONRenderer]

processors = base_processors + [dict_tracebacks, JSONRenderer()]
else:
processors = shared_processors + [ConsoleRenderer(colors=True)]
processors = base_processors + [
ConsoleRenderer(colors=True, exception_formatter=plain_traceback)
]

structlog.configure(
processors=processors,
Expand Down Expand Up @@ -68,7 +68,7 @@ async def validation_exception_handler(

@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception):
logger.error("unhandled_error", path=str(request.url), error=str(exc))
logger.error("unhandled_error", path=str(request.url), exc_info=exc)
return JSONResponse(
status_code=500,
content={"detail": "Internal Server Error"},
Expand Down
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ async def structured_log_middleware(request: Request, call_next):
log = structlog.get_logger()
log.error(
"request_failed",
exc_info=str(exc),
exc_info=exc,
status_code=500,
)
raise
Expand Down
46 changes: 46 additions & 0 deletions test/test_routers/test_logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from fastapi.testclient import TestClient

from main import app


def _client_with_failing_route():
"""Register a temporary route that raises, keeping the real app stack."""

def boom():
raise RuntimeError("boom real del endpoint")

app.add_api_route("/__boom_test", boom, methods=["GET"])
return TestClient(app, raise_server_exceptions=False)


def _remove_failing_route():
app.router.routes = [
route
for route in app.router.routes
if getattr(route, "path", None) != "/__boom_test"
]


def test_unhandled_exception_returns_500_json():
"""An unhandled exception must answer 500 with a JSON body, never an empty one."""
client = _client_with_failing_route()
try:
response = client.get("/__boom_test")

assert response.status_code == 500
assert response.json() == {"detail": "Internal Server Error"}
finally:
_remove_failing_route()


def test_unhandled_exception_logs_real_traceback(caplog):
"""The original traceback must reach the logs, not a masked or missing error."""
client = _client_with_failing_route()
try:
with caplog.at_level("ERROR"):
client.get("/__boom_test")

assert "boom real del endpoint" in caplog.text
assert "Traceback" in caplog.text
finally:
_remove_failing_route()
Loading