Java 使用 log4j 在日志文件中打印线程 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38072058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:59:48  来源:igfitidea点击:

Printing thread id in log file using log4j

javamultithreadinglogginglog4j

提问by Asim

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

我正在尝试在我的日志文件中打印正在为其完成日志记录的线程的 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>

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

现在我假设我可以在我的 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();
 } 
}

Any guidance would be aprreciated. Thanks

任何指导将不胜感激。谢谢

回答by Fildor

%tin the ConversionPattern gives you the thread's name.

%t在 ConversionPattern 中为您提供线程的名称。

Not the same as Thread ID but better than nothing and works without touching the code.

与线程 ID 不同,但总比没有好,并且无需接触代码即可工作。

Update:As yuugen's answer points out: in log4j 2.xthere is %tidfor thread id. (+1 for his answer from me, adding it here for completeness. If this helps you please upvote hisanswer!)

更新:正如 yuugen 的回答所指出的:在 log4j 2.x 中%tid线程 id。(对我的回答+1,将其添加到此处以确保完整性。如果这对您有帮助,请为他的回答点赞!)

回答by Sprooose

If you are using Log4j 1.x then you could create another class that implements the functions of Log4j. Modify the debug method to append the Thread Id to the message.

如果您使用的是 Log4j 1.x,那么您可以创建另一个实现 Log4j 功能的类。修改调试方法以将线程 ID 附加到消息中。

However, you will need to bulk replace Log4j definitions with a reference to your own log class, across your codebase. I assume you have a line at the top of your class file with something like:

但是,您需要在整个代码库中使用对您自己的日志类的引用来批量替换 Log4j 定义。我假设您的类文件顶部有一行内容,例如:

Logger log = Logger.getLogger(MyService.class.getName());

And that would need to be replaced with a reference to your class instead.

而这需要用对您的类的引用来代替。

As this class will be the only point that Log4j is now referenced in your Application, it makes it easy for you to replace the logging library if you ever wish to.

由于此类将是您的应用程序中现在引用 Log4j 的唯一点,因此如果您愿意,可以轻松替换日志库。