I would like to log correlation id in every log messages via Loguru. I tried to use logger.contextualize(correlation_id=id)
. It works in the parent thread but not the child thread. How do I get the correlation id to be logged in the child thread as well?
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')
Current output is
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 | {}
But I want it to be
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'}
Any insights?