gpt4 book ai didi

python - 记录协程感知变量

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:43 26 4
gpt4 key购买 nike

我正在遵循 asyncio.Queue 中给出的 worker 示例。在 worker_task() 调用的函数中,我想记录当前工作人员的姓名,而不必在任何地方传递它。

我怀疑通过 LoggerAdapterContextVar 的某种组合,它可以做我想做的事情。

接下来的事情......

import logging
logging.basicConfig(format="%(worker_name)s %(message)s")
logger = logging.getLogger(__name__)

async def sub_function():
logger.info("a message") # worker-1: a message

async def worker_task(queue, worker_name):
logger.do_something(worker_name) # HELP HERE PLEASE
await sub_function()

queue = asyncio.Queue()

workers = [
loop.create_task(worker_task(queue, "worker-1"),
loop.create_task(worker_task(queue, "worker-2"),
]

最佳答案

你可以使用这样的东西:

import logging
import asyncio
from contextvars import ContextVar

WorkerName = ContextVar('worker_name')

logging.basicConfig(format='%(worker_name)s %(message)s', level=logging.INFO)

class WorkerAdapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
kwargs.setdefault('extra', {})['worker_name'] = WorkerName.get()
return msg, kwargs

logger = WorkerAdapter(logging.getLogger(__name__), None)


async def sub_function():
logger.info('a message')

async def worker_task(worker_name):
WorkerName.set(worker_name)
await sub_function()

loop = asyncio.get_event_loop()

workers = [
loop.create_task(worker_task('worker-1')),
loop.create_task(worker_task('worker-2')),
]

loop.run_until_complete(asyncio.gather(*workers))

关于python - 记录协程感知变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55068373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com