0

アプリケーションで j2se ロガーを使用しています。現在のログ ステートメントを変更せずに、ログ ファイル内の各ログ エントリで jSessionId を記録する方法はありますか。

4

1 に答える 1

0

私はこれに対する解決策を得ました。これは、ThreadLocal、サーブレット フィルター、およびログ フィルターを使用して実行できます。手順は次のとおりです。

ThreadLocal 変数を使用してセッション ID ホルダー クラスを作成します。

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());

ServletFilter クラスの doFilter() メソッドの finally ブロック内に、以下の行を追加して、リクエストが処理された後に 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
于 2013-04-12T16:12:29.380 に答える