Apache LOG4J is used for logging in Java but apart from logging we can also set value inside log4j that can appear in all the logs getting generated. This will help us in debugging complex distributed applications. In this article we will use this technique to keep track of users activity during the login session.
In a multi threaded applications it would be difficult for us to keep track of different users logs, to distinguish users request we assign unique> Public Interface for Mapped Diagnostic Context:
package org.apache.log4j;
public>
// Put a context value (the o parameter) as>
// the current thread's context map.
static void put(String key, Object o);
// Get the context>
static Object get(String key);
// Remove or clear the context>
static void remove(String key)
}
The MDC> Conversion Pattern in LOG4J:
To implement MDC in log4j we would require to add some entry in Conversion Pattern, the new entry would be “%X“. The X conversion character must be followed by the key placed between braces, example: %X{client} here client is the key.
Example:
Here i have written an Servlet that accepts user from query string. We assign this query string to the session object, now the session holds the user, we than put the information that was stored in session to log4j by calling MDC.put(“client”,userId). After putting the value inside the MDC now whenever we call log statement, the userId will also get printed with the logs getting generated. MDC in log4j.properties:
Here in log4j.properties the only change we have to make is to add “%X{key}” inside the conversion Pattern. If you look in the above log4j.properties file code if have added “%X{client}”. Now when you run this code we get the following output.
2009-04-12 20:31:38,673 [http-8100-1] - Hitesh INFO Testing - Testing LOG Data