2013-02-27 61 views

回答

0

我爲此得到了解決方案。這可以通過使用ThreadLocal,一個servlet過濾器和一個日誌過濾器來完成。的步驟如下:

創建ThreadLocal變量的會話ID holder類:

public abstract class SessionUtil { 
     private static final ThreadLocal<String> sessionIdThreadLocal = new ThreadLocal<String>(); 
     public static String getSessionId() { 
      return sessionIdThreadLocal.get(); 
     } 
     public static void setSessionId(String jSessionId) { 
      sessionIdThreadLocal.set(jSessionId); 
     } 
     public static void removeSessionId() { 
      sessionIdThreadLocal.remove(); 
     } 
} 

創建ServletFilter中和ServletFilter中類的init()方法的內部,與所述記錄處理機連接日誌過濾器:

Handler[] handlers = Logger.getLogger("").getHandlers(); 
for (Handler handler : handlers) { 
LogFilter logFilter = new MyLogFilter(); 
handler.setFilter(logFilter); 
} 

裏面ServletFilter中類的doFilter()方法中,添加以下行JSESSIONID添加的ThreadLocal:

SessionUtil.setSessionId(request.getSession(false).getId()); 

內部的doFilter()在ServletFilter中類方法的最後塊中,添加以下線路從ThreadLocal的除去JSESSIONID的請求被處理之後:

SessionUtil.removeSessionId(); 

定義日誌過濾器類:

public class MyLogFilter implements LogFilter { 
    public boolean isLoggable(LogRecord record) { 
    if (SessionUtil.getSessionId() != null && 
      !SessionUtil.getSessionId().toString().equals("")) { 
     StringBuilder sessId = new StringBuilder(SessionUtil.getSessionId().toString()); 
     String methodName = record.getSourceMethodName(); 
      if (methodName != null && !methodName.equals("")) { 
      if (!methodName.endsWith(sessId.toString())) { 
        record.setSourceMethodName(sessId.insert(0, " ").insert(0, methodName).toString()); 
      } 
      } else { 
      record.setSourceMethodName(sessId.toString()); 
      } 
    } 
     return true; 
    } 
} 

現在樣本日誌條目將如下:

[4/12/13 10:00:46:685 EDT] 00000020 SampleClass I com.example.SampleClass sampleMethod() [ROatVgqdnLd-ls3_ONvXcXU] Sample message 
相關問題