2011-12-30 37 views
4

我有一個日誌類,有幾個靜態方法,幫助記錄有關我的程序的信息。如何知道哪個線程稱爲我的日誌方法?

我的問題是我有2個線程正在運行,並且他們都向我的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 2011-12-30 07:31:11

回答

8

添加到您的記錄:

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

和轉儲到日誌文件。

+0

太棒了!感謝dbf! – 2011-12-30 07:42:55

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 
} 
相關問題