使用 log4j 在日志文件中打印线程 ID
2022-09-02 11:09:10
我正在尝试在我的日志文件中打印正在为其执行日志记录的线程的ID。我在代码级别上做到了这一点,其中“log”是Logger类对象,但这不是我真正想要的。实际上,我的应用程序是一个大型分布式应用程序,不可能在代码中添加所有内容。无论如何,我都可以在我的log4j.xml文件中进行任何更改,并为代码中的每个 log.info 打印线程ID。这是我的log4j.xmllog.info(Thread.currentThread().getId())
Thread.currentThread().getId()
log.info("something")
<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>
现在我假设我可以在xml的布局中添加一些东西来打印线程。我还附加了示例代码,其中我正在尝试这样做只是为了参考
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();
}
}
任何指导都将得到批准。谢谢