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))
添加回答
举报