我正在尝试在我的日志文件中打印正在执行日志记录的线程的 ID。我通过 log.info(Thread.currentThread().getId())
在代码级别完成了它,其中“日志”是 Logger 类对象,但这不是我真正想要的。实际上我的应用程序是一个大型分布式应用程序,不可能在代码中添加 Thread.currentThread().getId()
和每个 log.info("something")
。无论如何,我可以通过它在我的 log4j.xml 文件中进行任何更改并为我的代码中的每个 log.info 打印线程 ID。这是我的 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>
现在我假设我可以在我的 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();
}
}
任何指导将不胜感激。谢谢
原文由 Asim 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 log4j 2 中 https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout
%tid
打印线程ID