Search code examples
multithreadingspring-bootlog4jlog4j2logback

Logging Thread ID instead of Thread Name using Logback


I have a Spring boot application and I'm using logback as the framework for logging. Currently I want to display thread id instead of the thread name. I know it is possible using log4j2 if you use %tid .

  • Can I achieve the same using logback or should I implement a Custom Thread ID extractor?

  • I'm extending PatternLayout class and creating a map which has the thread id and it's value. How do I use this key in my logback.xml


Solution

  • This can be done with a custom ClassicConverter, such as:

    import ch.qos.logback.classic.pattern.ClassicConverter;
    import ch.qos.logback.classic.spi.ILoggingEvent;
    
    public class ThreadIdConverter extends ClassicConverter {
      @Override
      public String convert(final ILoggingEvent e) {
        return String.valueOf(Thread.currentThread().getId());
      }
    }
    

    Then, in your logback.xml:

    <configuration>
      <conversionRule conversionWord="threadId" converterClass="ThreadIdConverter"/>
      ...
      <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
          <pattern>%threadId %msg%n</pattern>
        </encoder>
      </appender>
      ...
    </configuration>