Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 718
Aravind Avatar asked Jul 27 '26 11:07

Aravind


1 Answers

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>
like image 99
Seva Safris Avatar answered Jul 29 '26 22:07

Seva Safris