我们有一种设置线程名称的方法:然后在格式化程序thread = threading.Thread(name='Very important thread', target=foo)
中获取该名称以用于记录目的。%(thread)s:
有可能做这样的事情asyncio.Task
吗?
问问题
5169 次
2 回答
8
从 Python 3.8 开始,您可以在 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
例如:
asyncio.create_task(your_coro(), name="your task name")
# or
task = asyncio.create_task(your_coro())
task.set_name("your task name")
于 2020-01-26T01:02:11.690 回答
8
您可以通过以下方式访问当前任务:
asyncio.Task.current_task()
与任何其他 python 对象一样,您可以动态地将一些属性添加到Task
. 例如,将此添加到任何启动新任务的协程的第一行:
asyncio.Task.current_task().foo = "Bar"
asyncio.Task.current_task().name = "#{}".format(n)
添加一个日志过滤器以使用您的记录器输出此数据。
于 2017-01-22T21:36:56.733 回答