Logging Thread ID instead of Thread Name using Logback
Asked Answered
A

2

6

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

Add answered 14/4, 2020 at 12:3 Comment(0)
M
7

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>
Manometer answered 21/12, 2022 at 15:49 Comment(0)
C
0

By document of log4j2, you can use Pattern Layout as you know already. so just write %t on your configuration file in logback.xml reference document : Link and find Outputs the ID of the thread that generated the logging event.

In my case I use like this

<Configuration>
  ...
  <Appenders>
    ...
    <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] [%-5level] %logger{36} - %msg%n"/>
    ...
  </Appenders>
...
</Configuration>
Cly answered 4/5, 2020 at 6:34 Comment(1)
[%t] prints thread name not thread id with logback.Habitue

© 2022 - 2024 — McMap. All rights reserved.