The only way I can think of would be to write your own PrintStream
implementation which created a stack trace when the println
method was called, in order to work out the class name. It would be pretty horrible, but it should work... proof of concept sample code:
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");
}
}
(In your code you would make it log to log4j instead of course... or possibly as well.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…