When I call java.util.logging.Logger.log(Level, String) from a lambda, the java.util.logging.LogRecord.getSourceMethodName() method returns lambda$0 at my Formatter.
For instance:
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));
}
How can I get the method name (doStuff) instead 'lambda$0'?
PS.: I wouldn't like to get it from StackTrace.
From the 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.
Therefore, the way to solve your problem is to specify the class name and method name:
Logger logger = Logger.getLogger("myLog");
names.forEach(beatle -> logger.log(Level.SEVERE,
getClass().getName(), "doStuff", beatle));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With