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

我有一些库在我身上调用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

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

 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"); } } 

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

如果您可以修改源代码,那么请查看Eclipse插件Log4E 。 它提供了一个将System.out.println转换为logger语句的函数(以及处理日志记录的许多其他很酷的东西)。