【问题标题】:How do I know which Thread called my Log method?我怎么知道哪个线程调用了我的 Log 方法?
【发布时间】:2023-03-29 07:08:02
【问题描述】:

我有一个 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 );
     }
 }

【问题讨论】:

  • 为什么不使用现有的日志框架之一,例如 log4j(可能使用 apache commons logging 包装)?

标签: java multithreading logging


【解决方案1】:

将此添加到您的记录器:

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

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

【讨论】:

    【解决方案2】:
    public class Temp{
       static Thread t = null;
    }
    

    temp.t = Thread.currentThread();

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

    【讨论】:

      【解决方案3】:

      另外,对于pthreads,知道调用线程的函数是:pthread_t pthread_self (void);

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

      【讨论】:

      • 是的,我知道 OP 中没有提到 pthread,但它可能对其他人有所帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 2012-07-02
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2011-09-12
      相关资源
      最近更新 更多