我如何知道是哪个线程调用了我的Log方法?

4

我有一个Log类,其中有几个静态方法,可以帮助记录程序的信息。

我的问题是,我有2个线程在运行,并且它们都向我的Log类发送请求以记录信息。

我希望我的Log类显示哪些线程正在记录哪些行。

我该怎么做才能实现这个功能?

我的代码基本上是这样的:

 public class Log {
     public static void log ( String tag , Object message ) 
     {
         String lineToPrint = "";
         //Builds the string taking in time data and other information
         //...
         //This is where I want to see which thread called this log function
         //...

         System.out.println( lineToPrint );
     }
 }

2
为什么不使用现有的日志框架,比如log4j(可能使用apache commons logging进行封装)? - Thomas
3个回答

8

将以下内容添加到您的记录器中:

Thread t = Thread.currentThread();
String name = t.getName();

并将其转储到日志文件中。


0

是的,我知道OP没有提到pthread,但它可能会帮助其他人。 - Aquarius_Girl

0
public class Temp{
   static Thread t = null;
}

temp.t = Thread.currentThread();

 public static void log ( String tag , Object message ) 
 {
         temp.t.getName();//get it
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接