我有一些库正在对我调用 System.out.println,我想通过 log4j 或公共(public)日志记录来重定向它们。但特别是我想保留完全限定的类名,这样我就知道哪个组件生成了日志。
有没有一个好的、有序的方法来完成这个?
更新:完成此操作后,我将代码发布到此处:
http://www.bukisa.com/articles/487009_java-how-to-redirect-stderr-and-stdout-to-commons-logging-with-the-calling-class
最佳答案
我能想到的唯一方法是编写您自己的 PrintStream
实现,它在调用 println
方法时创建堆栈跟踪,以便计算出类(class)名称。这将是非常可怕的,但它应该可以工作......概念验证示例代码:
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 而不是……或者也可以。)
关于java - 将 System.out.println 重定向到 Log4J,同时保留类名信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5712764/