将System.out.println重定向到Log4J,同时保留类名信息

Dav*_*rks 4 java log4j slf4j apache-commons-logging

我有一些库在我身上调用System.out.println,我想通过log4j或commons日志记录重定向它们.但特别是我想保留完全限定的类名,以便我知道哪个组件生成了日志.

有一个很好的,有序的方法来实现这一目标吗?


更新:完成此操作后,我在此处发布了代码: http :
//www.bukisa.com/articles/487009_java-how-to-redirect-stderr-and-stdout-to-commons-logging-with-the-calling-class

Jon*_*eet 16

我能想到的唯一方法是编写自己的PrintStream实现,在调用println方法时创建堆栈跟踪,以便计算出类名.这将是非常可怕的,但它应该工作...概念证明示例代码:

import java.io.*;

class TracingPrintStream extends PrintStream {
  public TracingPrintStream(PrintStream original) {
    super(original);
  }

  // You'd want to override other methods too, of course.
  @Override
  public void println(String line) {
    StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    // Element 0 is getStackTrace
    // Element 1 is println
    // Element 2 is the caller
    StackTraceElement caller = stack[2];
    super.println(caller.getClassName() + ": " + line);
  }
}

public class Test {
  public static void main(String[] args) throws Exception {
    System.setOut(new TracingPrintStream(System.out));
    System.out.println("Sample line");
  }
}
Run Code Online (Sandbox Code Playgroud)

(在你的代码中,你会让它记录到log4j而不是当然......或者也可能.)