When writing Python asyncio programs, often there is an async function that have many invocations running concurrently. I want to add some logging to this function, but the logging output from different invocations will be interleaved, making it hard to follow. My current solution is to somehow create a unique name for each invocation, and log that name each time, like this:
async def make_request(args):
logger = logging.getLogger('myscript.request')
log_name = unique_name()
logger.debug('[%s] making request with args %r', log_name, args)
response = await request(args)
logger.debug('[%s] response: %r', log_name, response)
However, having to put log_name in every logging call gets tiring pretty quickly. To save those keystrokes, I came up with a different solution, creating a new logger with a unique name for each invocation:
async def make_request(args):
logger = logging.getLogger(f'myscript.request.{unique_name()}')
logger.debug('making request with args %r', args)
response = await request(args)
logger.debug('response: %r', response)
Are there any down sides to this approach? The only thing I can think of is that creating a new logger may be expensive, but is that actually the case? Are there any pitfalls I'm not seeing?