Logging User Session details using Apache log4j

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 identity each request and the same identity can be passed to log4j using Mapped Diagnostic Context (MDC). The log4j MDC automatically manages the identity set for different request.
Public Interface for Mapped Diagnostic Context:
package org.apache.log4j;
public class MDC {
    // Put a context value (the o parameter) as identified by key into
    // the current thread's context map.
    static void put(String key, Object o);
 
    // Get the context identified by key.  
    static Object get(String key);
 
    // Remove or clear the context identified by key.	
    static void remove(String key)
}

The MDC class contains only static methods, from the above code we understand that their will be unique key at application level and the Object holds the user session information. To read the user session we would use get Method and to remove the entry we would use remove method.
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:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.*;
 
public class Testing extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
package test.log4j.MDC;
 
static Logger log = Logger.getLogger(Testing.class);
 
protected void proce***equest(HttpServletRequest request, HttpServletResponse response) {
	String userId = "";
 
	if(request.getParameter("user") != null) {
		userId = request.getParameter("user");
	} else {
		userId = "";
	}
	request.getSession().setAttribute("user", userId);
	MDC.put("client", userId);
	log.info("Testing LOG Data");
	MDC.remove("client");
}
 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
	proce***equest(request, response);
}
 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
	proce***equest(request, response);
}
}

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:

log4j.logger.test.log4j.MDC = DEBUG, testing
log4j.appender.testing=org.apache.log4j.DailyRollingFileAppender
log4j.appender.testing.file=${catalina.home}/logs/test.log
log4j.appender.testing.datePattern='.'yyyy-MM-dd
log4j.appender.testing.layout=org.apache.log4j.PatternLayout
log4j.appender.testing.layout.conversionPattern=%d [%t] - %X{client} %-5p %c %x - %m

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

Here Hitesh is the data that comes from MDC.

좋은 웹페이지 즐겨찾기