LogRecord.getSourceMethodName() 返回 lambda$0
LogRecord.getSourceMethodName() returning lambda$0
当我从 lambda 调用 java.util.logging.Logger.log(Level, String)
时,java.util.logging.LogRecord.getSourceMethodName()
方法 returns lambda$0 在我的 Formatter
.
例如:
public void doStuff() {
List<String> names = new ArrayList<>();
names.add("John");
names.add("Paul");
names.add("George");
names.add("Ringo");
names.forEach((beatle) -> Logger.getLogger("myLog").log(Level.SEVERE, beatle));
}
如何获取方法名称 (doStuff) 而不是 'lambda[=23=]'?
PS.: 我不想从 StackTrace 获取它。
来自documentation of the Logger class:
For the methods that do not take an explicit source name and method name, the Logging framework will make a "best effort" to determine which class and method called into the logging method. However, it is important to realize that this automatically inferred information may only be approximate (or may even be quite wrong!). Virtual machines are allowed to do extensive optimizations when JITing and may entirely remove stack frames, making it impossible to reliably locate the calling class and method.
因此,解决您的问题的方法是指定class名称和方法名称:
Logger logger = Logger.getLogger("myLog");
names.forEach(beatle -> logger.log(Level.SEVERE,
getClass().getName(), "doStuff", beatle));
当我从 lambda 调用 java.util.logging.Logger.log(Level, String)
时,java.util.logging.LogRecord.getSourceMethodName()
方法 returns lambda$0 在我的 Formatter
.
例如:
public void doStuff() {
List<String> names = new ArrayList<>();
names.add("John");
names.add("Paul");
names.add("George");
names.add("Ringo");
names.forEach((beatle) -> Logger.getLogger("myLog").log(Level.SEVERE, beatle));
}
如何获取方法名称 (doStuff) 而不是 'lambda[=23=]'?
PS.: 我不想从 StackTrace 获取它。
来自documentation of the Logger class:
For the methods that do not take an explicit source name and method name, the Logging framework will make a "best effort" to determine which class and method called into the logging method. However, it is important to realize that this automatically inferred information may only be approximate (or may even be quite wrong!). Virtual machines are allowed to do extensive optimizations when JITing and may entirely remove stack frames, making it impossible to reliably locate the calling class and method.
因此,解决您的问题的方法是指定class名称和方法名称:
Logger logger = Logger.getLogger("myLog");
names.forEach(beatle -> logger.log(Level.SEVERE,
getClass().getName(), "doStuff", beatle));