Last active
July 27, 2023 06:47
-
-
Save Olegt0rr/5439c8c1f340da118b79edffa43dbc00 to your computer and use it in GitHub Desktop.
aiohttp single log record traceback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from traceback import TracebackException | |
from aiohttp import web | |
from aiohttp.abc import StreamResponse | |
from aiohttp.typedefs import Handler | |
from aiohttp.web_exceptions import HTTPException | |
logger = logging.getLogger(__name__) | |
routes = web.RouteTableDef() | |
CAPTURE_LOCALS = True # get it from .env / settings | |
@web.middleware | |
async def error_middleware(request: web.Request, handler: Handler) -> StreamResponse: | |
"""Process all unhandled exceptions.""" | |
try: | |
return await handler(request) | |
# upstream http-based exceptions (e.g. raised 404) | |
except HTTPException: | |
raise | |
# catch real exceptions | |
except Exception as exc: | |
tb = _prepare_traceback(exc) | |
logger.error("Handled exception! %s", tb) | |
return web.Response(text="Something went wrong (apology text)", status=500) | |
def _prepare_traceback(exc: Exception) -> str: | |
"""Prepare readable traceback.""" | |
tb_exc = TracebackException.from_exception(exc, capture_locals=CAPTURE_LOCALS) | |
return "\n".join(tb_exc.format()) | |
@routes.get("/") | |
async def bad_handler(request: web.Request): | |
"""Brake everything!""" | |
foo = "foo" | |
bar = {"some": "data"} | |
return foo / bar | |
if __name__ == "__main__": | |
app = web.Application(middlewares=[error_middleware]) | |
app.add_routes(routes) | |
web.run_app(app) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
При необходимости можно разместить в нём инструменты дебаг-логирования