我想通过Loguru在每个日志消息中记录相关性ID。我尝试使用logger.contextualize(correlation_id=id)
。它在父线程中工作,但在子线程中不工作。我如何获得在子线程中记录的相关性ID?
logger.remove(0)
logger.add(sys.stderr, format="{time:MMMM D, YYYY HH:mm:ss} | {level} | {message} | {extra}")
class Client:
def get_data(self):
logger.info("get_data")
class ProcessThread(threading.Thread):
def __init__(self, client):
threading.Thread.__init__(self)
self.client = client
def run(self):
logger.info("inside child thread")
self.client.get_data()
def test(id):
with logger.contextualize(correlation_id=id):
process_thread = ProcessThread(Client())
logger.info("inside parent thread")
process_thread.start()
test('101')
电流输出为
January 17, 2023 21:14:08 | INFO | inside parent thread | {'correlation_id': '101'}
January 17, 2023 21:14:08 | INFO | inside child thread | {}
January 17, 2023 21:14:08 | INFO | get_data | {}
但我希望它是
January 17, 2023 21:14:08 | INFO | inside parent thread | {'correlation_id': '101'}
January 17, 2023 21:14:08 | INFO | inside child thread | {'correlation_id': '101'}
January 17, 2023 21:14:08 | INFO | get_data | {'correlation_id': '101'}
有什么见解吗?
1条答案
按热度按时间5uzkadbs1#
您没有在get_data()和run()中提供上下文信息。
只要为他们两个都执行
with logger.contextualize(correlation_id=id):
,它应该会工作。logger.contextualize在你离开
with
时丢失上下文