我有一些库在我身上调用System.out.println,我想通过log4j或commons logging重定向它们。但是我特别想保留完全限定的类名,这样我就知道是哪个组件生成了日志。
有一个好的,有序的方法来完成这一点吗?
更新:完成后,我在这里发布了代码:
http://www.bukisa.com/articles/487009_java-how-to-redirect-stderr-and-stdout-to-commons-logging-with-the-calling-class
我能想到的唯一方法是编写自己的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");
}
}
(在您的代码中,您将使其日志到log4j,而不是当然…或者也可以。)
如果您可以修改源代码,那么请查看Eclipse Plugin Log4E。它提供了一个函数将System.out.println转换为日志记录语句(以及许多其他处理日志记录的很酷的东西)。