I have a server application for handling XMLRPC requests. Each connection creates its own thread. I would like to setup logging so that some thread/connection specific information gets in the log. I could do something like:
import logging
@add_unique_request_id
def thread_top(request_id):
logging.info('thread %d says: hello'%request_id)
logging.error('thread %d says: darn!!'%request_id)
and setup the global root logger as I wish, but I do not like this solution. I would like the following instead:
import logging
@setup_logger
def thread_top():
logging.info('hello')
logging.error('darn!!')
But I have no idea how the setup_logger deco should look like. I came up with a workaround to use separate process for each request, then setting the root logger in each process would do exactly what I want. Is there some way to make this work without being forced to use multiprocessing?
Thank you!
I’m doing this with a custom formatter and threadlocal storage:
Then in logger configuration:
Before logging the context is populated with:
You may want to use different formatters for different parts of application where you might not need
request_idin the log records.