I am trying to print the id of the thread for which the logging is being done in my logfile. I did it at code level by log.info(Thread.currentThread().getId())
where "log" is Logger class object but this is not what i exactly want. Actually my application is a large distributed application and it is not possible to add Thread.currentThread().getId()
with every log.info("something")
in the code. Is there anyway by which i can just make any change in my log4j.xml file and print threads id for every log.info in my code. This is my log4j.xml
<log4j:configuration debug="true">
<!-- File Appenders -->
<appender name="EventsAndErrorsFileAppender" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="EventsAndErrors.xml" />
<param name="Datepattern" value="'.'yyyy-MM-dd-HH" />
<param name="MaxFileSize" value="1000KB" />
<param name="MaxBackupIndex" value="140" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%C] %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="ERROR" />
</filter>
</appender>
<root>
<priority value="debug" />
<appender-ref ref="EventsAndErrorsFileAppender" />
<appender-ref ref="ExceptionFileAppender" />
</root>
Now i am assuming that I can add something in my Layout in xml to print the thread. I am also attaching the sample code in which i am trying this just for reference
import org.apache.log4j.Logger;
class MyThread extends Thread implements MyInterface
{
public void run()
{
int i = 0;
while(i < 10)
{
System.out.println(Thread.currentThread().getId()+"In first thread");
log.info(Thread.currentThread().getId());
log.error(Thread.currentThread().getId());
System.out.println();
i++;
}
}
}
class MyThread1 extends Thread implements MyInterface
{
public void run()
{
int i = 0;
while(i < 10)
{
System.out.println(Thread.currentThread().getId()+"In secound thread");
log.info(Thread.currentThread().getId());
log.debug("debug");
System.out.println();
i++;
}
}
}
public class MyClass implements MyInterface
{
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread1 = new MyThread();
MyThread1 thread2 = new MyThread1();
log.info("logging stareted");
thread1.start();
thread2.start();
}
}
Any guidance would be aprreciated. Thanks
%t
in the ConversionPattern gives you the thread's name.
Not the same as Thread ID but better than nothing and works without touching the code.
Update: As yuugen's answer points out: in log4j 2.x there is %tid
for thread id. (+1 for his answer from me, adding it here for completeness. If this helps you please upvote his answer!)
In log4j 2 https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout
%tid
prints the thread ID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With