日志框架打印的信息,前面出现的类名,方法名,在配置文件里可以进行配置,那它是从哪里拿到的信息呢?
抽出来一个题目,实现一个函数,打印调用方的信息,类名,方法名等。
例如:
public class Caller {
public static void main(String[] args) {
printCallerInfo();
}
private static void printCallerInfo() {
// TODO
// 打印结果应该是 main
}
}
这些信息在 Java 这种运行时保留调用栈的语言中,只要直接从 StackTrace
里往外拿信息就可以了,具体如下:
public class Caller {
public static void main(String[] args) {
printCallerInfo();
}
private static void printCallerInfo() {
Throwable t = new Throwable();
StackTraceElement caller = t.getStackTrace()[1];
System.out.println(caller.getClassName() + "#" + caller.getMethodName());
}
}
查看 JDK 的 java.util.logging.LogRecord#inferCaller
方法,可以看到实现就是这样的。
// Private method to infer the caller's class and method names
private void inferCaller() {
needToInferCaller = false;
JavaLangAccess access = SharedSecrets.getJavaLangAccess();
// 主要就是下面的,通过 throwable 拿到 StackTrace 信息
Throwable throwable = new Throwable();
int depth = access.getStackTraceDepth(throwable);
boolean lookingForLogger = true;
for (int ix = 0; ix < depth; ix++) {
// Calling getStackTraceElement directly prevents the VM
// from paying the cost of building the entire stack frame.
StackTraceElement frame =
access.getStackTraceElement(throwable, ix);
String cname = frame.getClassName();
boolean isLoggerImpl = isLoggerImplFrame(cname);
if (lookingForLogger) {
// Skip all frames until we have found the first logger frame.
if (isLoggerImpl) {
lookingForLogger = false;
}
} else {
if (!isLoggerImpl) {
// skip reflection call
if (!cname.startsWith("java.lang.reflect.") && !cname.startsWith("sun.reflect.")) {
// We've found the relevant frame.
setSourceClassName(cname);
setSourceMethodName(frame.getMethodName());
return;
}
}
}
}
// We haven't found a suitable frame, so just punt. This is
// OK as we are only committed to making a "best effort" here.
}