Reputation: 741
Once the client login to my protal, I append the user id in the message, for all the log messages printed for the user. Is there any way that i can able to append the user id in a common place? instead of appending in line.
This is want i am doing right now...
LOGGER.info("client_id: "+client_id + " : Saving options..);
LOGGER.debug("client_id: "+client_id + " : return options are "+optionList);
Upvotes: 0
Views: 448
Reputation: 741
http://veerasundar.com/blog/2009/10/log4j-mdc-mapped-diagnostic-context-what-and-why/
How to differentiate log statements with respective to each clients? To avoid the log statements mix-in, we could add a user name (or some other data which will be unique to each client) to our log statements. To do this, we have to make sure that we pass this user name data explicitley to each and every log statements, which is a tedious and repetitive work. But, no need to worry! Log4j has an excellent way to overcome this. It’s called as MDC or Mapped Diagnostic Context.
So, What is Log4j MDC (Mapped Diagnostic Context) To put it simple, the MDC is a map which stores the context data of the particular thread where the context is running. To explain it, come back to our simple application – every client request will be served by different thread of the MyServlet. So, if you use log4j for logging, then each thread can have it’s own MDC which is global to the entire thread. Any code which is part of that thread can easily access the values that are present in thread’s MDC.
So, how do we make MDC to differentiate logging statements from multiple clients? Simple : Before starting any business process in your code, get the user name (for our Servlet, we can get it from request object) and put that into MDC. Now the user name will be available to the further processing. In your log4j.properties while defining the ‘conversionPattern’, add a pattern %X{key} to retrievce the values that are present in the MDC. The key will be ‘userName’ in our example. It’s like getting a value from a Session object.
Upvotes: 2