2011-12-30 2 views
4

私は、自分のプログラムに関する情報を記録するのに役立ついくつかの静的メソッドを持つLogクラスを持っています。どのスレッドがMy Logメソッドを呼び出したのかをどのように知ることができますか?

私の問題は、私は2つのスレッドを実行しており、両方の情報を記録するログクラスに要求を送信することです。

Logクラスでどのスレッドがどの行を記録しているかを表示したいと思います。

この機能を実現するにはどうすればよいですか?

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

とファイルをログに記録することをダンプ:

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

なぜあなたのような既存のログフレームワークの1つを使用していませんlog4j(おそらく、Apacheのコモンログを使用してラップされます)? – Thomas

答えて

8

があなたのロガーにこれを追加します。

私のコードは次のように基本的です。

+0

驚くばかり!ありがとうdbf! –

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 
} 
0

はまた、pthread Sに対して、呼び出し元のスレッドについて知るための機能は次のとおりです。pthread_t pthread_self (void);

参考:http://pubs.opengroup.org/onlinepubs/007908799/xsh/pthread_self.html

+0

ええ、私はpthreadsがOPに言及されていないが、それは他の誰かを助けるかもしれないことを知っています。 –

関連する問題