0

I would like to write common method for all my Logger.debug("") occurances.

public void debug(String message){
  if(Logger.isDebugEnabled()){
    LOGGER.debug(message);
  }
}

and in the same class I would be able to invoke this method to print any debug line.

debug("Into method xyz"); 
...
debug("exiting method xyz");

If I invoke like this, every debug line in the logs displaying the method line number instead of original line number. Is there any way to print actual line number from where it raised.

yassadi
  • 524
  • 1
  • 9
  • 20
Sekhar
  • 1
  • 2

1 Answers1

0

There is no point in doing what you are proposing.

Have a look at the source code of the Log4j Logger class (actually, its superclass Category, where the relevant logic is)

729   public
730   boolean isDebugEnabled() {
731     if(repository.isDisabled( Level.DEBUG_INT))
732       return false;
733     return Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel());
734   }

Then check the debug method itself:

252   public
253   void debug(Object message) {
254     if(repository.isDisabled(Level.DEBUG_INT))
255       return;
256     if(Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel())) {
257       forcedLog(FQCN, Level.DEBUG, message, null);
258     }
259   }

As you see, the method debug already does exactly the same check as isDebugEnabled(). If you are only logging a single constant string that you are not constructing at that point, then there is zero reason to call isDebugEnabled() before calling debug().

If however, you are constructing your log message, and this takes time, then there is a reason:

if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("The 3-millionth digit of PI is " + calculatePiDigit(3000000));
}

However, in that case, you cannot instead call your method debug from your question, because that would defeat the purpose:

debug("The 3-millionth digit of PI is " + calculatePiDigit(3000000));

would always do a lengthy calculation, regardless of whether debug logging is enabled or not.

To answer your question:

No, it's not possible to get the line number correct in the situation that you propose. However, there is also no benefit to your application from the situation that you propose. So, it's not a problem.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79