I have a logging problem that I can't sort out in a simple way and I think is quite common.
As I have many concurrent users doing with different transactions, I would like to identify every single line that I log with an id that helps me to identify who the user was. May be the session id (but note that some classes that log don't have access to the context or any 'standard' shared resource.
I can't think of a simple solution, maybe create a wrapper setting the name of the thread (how?) or adding the session id to the thread and retrieving it?
What if you expanded your methods to include a parameter of 'String username' and then passed the username from the controller? Then you could prepend/append the username to the log text. If you do this, just make sure that you handle the case where the session expires and your username may be null/undefined.
> information that you can use to identify a user? (I'm guessing... no)
Sorry, my fault. I don't care too much (well, that would be nice) to identify the user straight away, I just need to be to say which line of code are coming from the same user (or session) and which are not in a timespan of 2-3 seconds where I may have few hundreds lines...
Threads go back into the pool between requests. Would you need something to re-initialize it on new requests?
I would not worry about re-initializing because, we are trying to track the log messages *per request*. So irrespective of whether the threads are sent back to pool between requests, we would be populating the MDC on *every request*, may be in a servlet filter. Something like:
Principal user = httprequest.getUserPrincipal();
String strUser = user.getName();
So irrespective of whether the thread is the same or different one, i will be populating my MDC with the username so that this will be available as long as the request spans.
I guess, your concern would be valid if the thread was sent back to pool when the *current request* is still being processed.
These are just my thoughts with whatever little understanding i have about MDC. Feel free to correct me if i have got this wrong.