Example – getting loggers for callers

In Java, we use an API to get Logger. Using the API, a module can provide an implementation for the service LoggerFinder, which in turn can return Logger implementing the getLogger() method. This eliminates the dependency of libraries on specific loggers or logger facades, which is a huge advantage. The smaller but still annoying issue requiring us to write the name of the class again as the parameter to the getLogger() method remains.

To avoid this cumbersome task, we create a helper class that looks up the caller class and retrieves the logger that is suitable for the caller class and module. Because in this case there is no need for all the classes referenced in the stack trace, we will call the getCallerClass() method of the StackWalker class. We create a class named Labrador in the packt.java9.deep.stackwalker.logretrieve package:

package packt.java9.deep.stackwalker.logretriever;
import java.lang.System.Logger;
import java.lang.System.LoggerFinder;
import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE;

public class Labrador {
public static Logger retrieve() {
final Class clazz = StackWalker
.getInstance(RETAIN_CLASS_REFERENCE)
.getCallerClass();
return LoggerFinder.getLoggerFinder().getLogger(
clazz.getCanonicalName(), clazz.getModule());
}
}

Prior to Java 9, the solution for this issue was getting the StackTrace array from the Thread class and looking up the name of the caller class from there. Another approach was extending SecurityManager, which has a protected method, getClassContext(), which returns an array of all the classes on the stack. Both solutions walk through the stack and compose an array although we only need one element from the array. In the case of Logger retrieval, it may not be a significant performance penalty since loggers are usually stored in private static final fields and thus are initialized once per class during class initialization. In other use cases, the performance penalty may be significant.

Next, we will look at the details of StackWalker.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset