We have a way to set thread name: thread = threading.Thread(name='Very important thread', target=foo)
and after that get this name for logging purposes with %(thread)s:
in formatter.
Is it possible to do something like this with asyncio.Task
?
You can access the current task with:
asyncio.Task.current_task()
As any other python object, you can dynamically add some properties to a Task
. For example, add this to the first line of any of your coroutines that start a new task:
asyncio.Task.current_task().foo = "Bar"
asyncio.Task.current_task().name = "#{}".format(n)
Add a logging filter to output this data with your logger.
As of Python 3.8 you can name your tasks in asyncio
https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task
https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name
For example:
asyncio.create_task(your_coro(), name="your task name")
# or
task = asyncio.create_task(your_coro())
task.set_name("your task name")
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