Open vytas7 opened 1 month ago
I don't think there is any need to use threadlocal or contextvar. just use req
or resp
context
.
re-reading all that page it proposes several approaches. so yes, context var is better than threadlocal
Indeed, using global thread-locals is usually not a very bright idea and it leads to a spaghetti code base. But sometimes, particularly when working with a code base migrated from another framework that builds on this paradigm, or when very deep inside nested code, it might be a useful escape hatch.
contextvars
is a newer module in the stdlib (3.7+) that is more advanced thantheading.local()
as it not only understand threads, but alsoasyncio
coroutines, etc.Update the Request ID Logging recipe to use
contextvars
.Edit: also add tests for this recipe.