Class ExecutionContextTurboFilter

java.lang.Object
ch.qos.logback.core.spi.ContextAwareBase
ch.qos.logback.classic.turbo.TurboFilter
com.streamconverter.logging.ExecutionContextTurboFilter
All Implemented Interfaces:
ch.qos.logback.core.spi.ContextAware, ch.qos.logback.core.spi.LifeCycle

public class ExecutionContextTurboFilter extends ch.qos.logback.classic.turbo.TurboFilter
ExecutionContextからMDCに値を自動設定するLogback TurboFilter

このフィルターは、ログ出力の都度ExecutionContextHolderから値を取得し、 MDCに自動的に設定します。これにより、アプリケーションコードは MDC同期を意識する必要がありません。

設定例(logback.xml):


 <configuration>
   <turboFilter class="com.streamconverter.logging.ExecutionContextTurboFilter"/>

   <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
     <encoder>
       <pattern>%d{HH:mm:ss.SSS} [userId:%X{userId}] - %msg%n</pattern>
     </encoder>
   </appender>
 </configuration>
 

動作:

  1. ログ出力の都度、このフィルターのdecide()メソッドが呼ばれる
  2. ExecutionContextHolderから現在のExecutionContextを取得
  3. 共有コンテキストの全キーについて、MDCと比較して変更がある場合のみ更新
  4. 削除されたキーはMDCからも削除

パフォーマンス最適化:

  • MDCの値と比較して、変更がある場合のみMDC.put()を呼ぶ
  • 前回同期したキーをThreadLocalで追跡し、削除されたキーをクリーンアップ
  • 任意の数の共有コンテキストキーに対応

スレッドセーフ性: ThreadLocalを使用しているため、スレッドごとに独立したMDC値が設定されます。

  • Field Summary

    Fields inherited from class ch.qos.logback.core.spi.ContextAwareBase

    context
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    ch.qos.logback.core.spi.FilterReply
    decide(org.slf4j.Marker marker, ch.qos.logback.classic.Logger logger, ch.qos.logback.classic.Level level, String format, Object[] params, Throwable t)
    ログイベント処理時に呼ばれ、ExecutionContextの共有コンテキストをMDCに同期します

    Methods inherited from class ch.qos.logback.classic.turbo.TurboFilter

    decide, getName, isStarted, setName, start, stop

    Methods inherited from class ch.qos.logback.core.spi.ContextAwareBase

    addError, addError, addInfo, addInfo, addStatus, addWarn, addWarn, getContext, getDeclaredOrigin, getStatusManager, setContext

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

  • Method Details

    • decide

      public ch.qos.logback.core.spi.FilterReply decide(org.slf4j.Marker marker, ch.qos.logback.classic.Logger logger, ch.qos.logback.classic.Level level, String format, Object[] params, Throwable t)
      ログイベント処理時に呼ばれ、ExecutionContextの共有コンテキストをMDCに同期します

      共有コンテキストの全キーについて、現在のMDC値と比較し、変更がある場合のみ更新します。 前回存在していたが今回削除されたキーは、MDCからも削除されます。

      Specified by:
      decide in class ch.qos.logback.classic.turbo.TurboFilter
      Parameters:
      marker - マーカー
      logger - ロガー
      level - ログレベル
      format - メッセージフォーマット
      params - パラメータ
      t - 例外
      Returns:
      FilterReply.NEUTRAL(フィルタリングは行わず、常にログを通過させる)