Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A correct/common way to log async calls

Let's say we have a some async call of IO operation and we want to log it. The simplest way looks like this:

async def f():
   logger.log('io was called')
   await call_some_io()

But we obviously could hit the situation when we run log() function which switched a context and logged something else and only after this executed call_some_io().

Next approach looks more robust:

async def f():
   await call_some_io()
   logger.log('io was called')

We are waiting for call_some_io() and after it we are logging it. Looks like in this case we have consistent calls.

But there is a third way to use context manager:

async def f():
   with LoggingContext:
     await call_some_io()

And the LoggingContext here is some ContextManager where __exit__ method has some logging calls.

So the question is: which approach for logging asynchronous calls is most common and robust?

like image 865
Paul Avatar asked Sep 14 '25 05:09

Paul


1 Answers

All approaches are robust. The context manager might not be as common, but robust nevertheless.

However, examples #1 and #2 have different semantics. The first log message should read about to call io and not io was called, because no call has been issued yet.

The LoggingContext example is rather convenient for developers but equals example #2 in terms of execution order.

like image 52
Fabian Avatar answered Sep 16 '25 18:09

Fabian