Skip to content
Advertisement

How to wrap logging methods for Logger without lossing the name of the caller method?

I am trying to add some convenient methods to java.util.Logger. They are methods that I expect to ease the coding o my next Java application:

public void severeException(Exception e, String msg) {
  super.severe(msg);
  super.severe(e.getClass().getCanonicalName());
  super.severe(e.getMessage());
}

public void severeLoadingFile(Exception e, String filePath) {
  super.severe("Could not load file '" + filePath + "'");
  super.severe(e.getClass().getCanonicalName());
  super.severe(e.getMessage());
}

public void severeLoadingFile(String filePath) {
  super.severe("Could not load file '" + filePath + "'");
}

They represent a 1:2 to 1:3 ratio in the number of code lines I have to write whenever I want to report an exception. There are a large bunch of similar methods for well-known exceptions, like IOException loading a file, etc.

So far I have tried extending Logger as CustomLogger, which led me to problems with class loaders and modules when calling getLogger() method. Then I tried initializing CustomLogger by its constructor…

Beyond the problems with constructor and class loaders, this does not seem to be the way, as the caller method gets trapped by my wrapping methods.

I have scanned the Logger source code but did not find an easy way of calling log() passing it the caller’s name or something similar.

Any idea?

Advertisement

Answer

It is not impossible yet may impact performance. In your logging method you can find the caller’s name via the stack trace element (https://docs.oracle.com/javase/8/docs/api/java/lang/StackTraceElement.html).

System.out.println(Thread.currentThread().getStackTrace()[1]);

I second Anders’s idea of making proper use of a logging framework.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement