Beispiel #1
0
class MetisLogger:
    """Metis logging and trazability class.

    Setup all the neccesary logging facilities, such as:

    - Setting up loggers
    - Configure loglevels on aiohttp
    - Setup sentry
    - Add trazability headers

    With aiohttp_request we enable automatic coroutine logging.

    This contradicts twelve-factor's logging section, but it's useful on environments
    """
    @classmethod
    def setup(cls, app):
        """Setup app logging.

        By default it'll:

        - Setup a logfile for debug, json format
        - Setup a logfile for info to error, "human-readable" format
        - Setup a logfile for error+, "human-readable" format
        """
        app.setup_logger(logger)

        class InterceptHandler(logging.Handler):
            def emit(self, record):
                # Get corresponding Loguru level if it exists
                try:
                    level = logger.level(record.levelname).name
                except ValueError:
                    level = record.levelno

                # Find caller from where originated the logged message
                frame, depth = logging.currentframe(), 2
                while frame.f_code.co_filename == logging.__file__:
                    frame = frame.f_back
                    depth += 1

                logger.opt(depth=depth, exception=record.exc_info).log(
                    level, record.getMessage())

        logging.basicConfig(handlers=[InterceptHandler()], level=0)
        return logger

    @classmethod
    def get_middlewares(cls, app):
        """Setup all logging related middlewares"""
        if dsn := app.env('SENTRY_DSN', None):
            sentry_sdk.init(dsn=dsn, integrations=[AioHttpIntegration()])

        return [middleware_factory(), log_middleware]
Beispiel #2
0
    async def go(side_effect):
        async def hello(request):
            await side_effect()

            return web.Response(text=request['text'])

        app = web.Application(middlewares=[middleware_factory()])
        app.router.add_get('/', hello)

        client = await aiohttp_client(app)

        response = await client.get('/')

        assert response.status == 200

        text = await response.text()

        return text

def thread():
    assert grequest['sense'] == 42


async def task():
    # grequest is `lazy` version of request
    assert grequest['sense'] == 42

    loop = asyncio.get_event_loop()
    # works for threads as well with ThreadContext
    await loop.run_in_executor(None, ThreadContext(thread))


async def hello(request):
    # get_request is on-demand function to get current request
    assert get_request() is request

    request['sense'] = 42

    # asyncio.Task is supported
    await asyncio.ensure_future(task())

    return web.Response(text="Hello, world")


app = web.Application(middlewares=[middleware_factory()])
app.add_routes([web.get('/', hello)])
web.run_app(app)