javalogginglog4jlog4j2threadcontext

Alternative to 'ThreadContext' in log4j


I have been working on a project which uses log4j2, and in this project I use ThreadContext. Now I'm back to working with log4j (1), and it doesn't provide ThreadContext. Are there any good alternatives that I can ThreadContext with? Google searches hasn't given my any good ideas yet, so I hope someone here might have some input.


Solution

  • You can use MDC (Mapped Diagnostic Context) directly. See here for more details. Also see this example on how to use it.

    Basically you will set your attribute using:

    MDC.put("userName", "test");
    

    And then in the logger you can log that information like:

    #note the %X{userName} - this is how you fetch data from Mapped Diagnostic Context (MDC)
    log4j.appender.consoleAppender.layout.ConversionPattern = %-4r [%t] %5p %c %x - %m - user: %X{userName}%n
    

    Or if using xml config, you can configure a separate appender with a filter for that user, like:

    <appender name="Test" class="org.apache.log4j.DailyRollingFileAppender">
            <param name="File" value="my.log" />
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern"
                       value="[%d{HH:mm:ss.SSS}] %-8p [%-5t] %C{2}:%-12M - %m%n user: %X{userName}" />
            </layout>
            <filter class="org.apache.log4j.varia.StringMatchFilter">
                      <param name="StringToMatch" value=" user: test " />
                      <param name="AcceptOnMatch" value="true" />
              </filter>
        <filter class="org.apache.log4j.varia.DenyAllFilter"/>
        </appender>
    

    And then enable a logger only for that appender:

    <logger name="com.example.Clazz" additivity="false">
        <level value="info" />
        <appender-ref ref="Test"/>
    </logger>
    

    This way you can see the logs related only to user test.