Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set name for asyncio task?

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?

like image 242
El Ruso Avatar asked Jan 22 '17 17:01

El Ruso


2 Answers

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.

like image 82
Udi Avatar answered Sep 29 '22 10:09

Udi


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")
like image 36
Ellis Percival Avatar answered Sep 29 '22 09:09

Ellis Percival