猿问

记录协程感知变量

我正在关注asyncio.Queue. 在由worker_task()我调用的函数中,我想记录当前的工作人员姓名,而不必将其传递到任何地方。


我经历的某种组合怀疑LoggerAdapter,并ContextVar可以做我想做的。


以下内容...


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"),

]


达令说
浏览 164回答 1
1回答

心有法竹

你可以使用这样的东西:import loggingimport asynciofrom contextvars import ContextVarWorkerName = 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, kwargslogger = 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))
随时随地看视频慕课网APP

相关分类

Python
我要回答