为了账号安全,请及时绑定邮箱和手机立即绑定

记录协程感知变量

记录协程感知变量

达令说 2021-11-30 17:01:39
我正在关注asyncio.Queue. 在由worker_task()我调用的函数中,我想记录当前的工作人员姓名,而不必将其传递到任何地方。我经历的某种组合怀疑LoggerAdapter,并ContextVar可以做我想做的。以下内容...import logginglogging.basicConfig(format="%(worker_name)s %(message)s")logger = logging.getLogger(__name__)async def sub_function():    logger.info("a message") # worker-1: a messageasync 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"),]
查看完整描述

1 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

你可以使用这样的东西:


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


查看完整回答
反对 回复 2021-11-30
  • 1 回答
  • 0 关注
  • 163 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信