我能想到的唯一方法是編寫自己的PrintStream
實現,該實現在調用println
方法時創建堆棧跟蹤,以便計算出類名。這將是非常可怕的,但它應該工作...的概念的示例代碼證明:(。在你的代碼將使得其記錄到的log4j而不是當然...或者可能還有)
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");
}
}
如果我刪除了實現中的鎖定行爲以提高應用程序的性能,那麼會有什麼影響? – 2017-04-29 06:49:00