1

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?

coterobarros
  • 941
  • 1
  • 16
  • 25
  • 1
    You should consider using SLF4J together with some java logging framework as it makes it easier for you to use any logging logging framework without any changes to your code. Secondly, the Logger class is not easily extendable, and you probably don't want that. See answers to this question: https://stackoverflow.com/q/9630616/5047819 – Anders Lindgren Aug 22 '21 at 19:00

1 Answers1

1

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.

Queeg
  • 7,748
  • 1
  • 16
  • 42
  • Thank you. That's what I did: leaving the idea of extending Logger. I am making use of the `log` method that accepts an exception. However, before leaving, I found a public `logp` method in the source code of Logger that had `sourceClass` and `sourceMethod` as input parameters. – coterobarros Aug 24 '21 at 06:47
  • See https://www.tabnine.com/code/java/methods/java.util.logging.Logger/logp – coterobarros Aug 24 '21 at 06:48