我能想到的唯一方法是编写自己的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 而不是……或者也可以。)