Logging User Session details using Apache log4j
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.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
양식 제출 후 제출 버튼 비활성화텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.