Home > Mobile >  How to avoid writing `await` every time
How to avoid writing `await` every time

Time:11-19

When I use aiologger, I have to write await logger many times.

For example,

import asyncio
from aiologger import Logger


async def main():
    logger = Logger.with_default_handlers(name='my-logger')

    await logger.debug("debug at stdout")
    await logger.info("info at stdout")

    await logger.warning("warning at stderr")
    await logger.error("error at stderr")
    await logger.critical("critical at stderr")

    await logger.shutdown()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

It would be great if I could write something like al instead of await logger.

CodePudding user response:

async def main():
    logger = Logger.with_default_handlers(name='my-logger')

    async def al(s1: str, s2: str):
        await getattr(logger, s1)(s2)

    al("debug", "debug at stdout")
    al("info", "info at stdout")
    # ...etc

Disclaimer: I'm not saying that this is a good idea, or that I would enjoy maintaining a program written in this style.

Also, my text editor has good macro capability...

  • Related