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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With