On Jan 26, 2009, at 4:27 PM, Brian Hawkins wrote:

I've liked the log4j Logger except for two things. The first is that I have
to pass my class name to the logger when I get it, for example:

private static Logger myLogger = Logger.getLogger(MyClass.class);

This is fine but it is prone to cut and paste errors. A better solution is
to add the following getLogger method to Logger:

static
 public
 Logger getLogger() {
   StackTraceElement[] stack = Thread.currentThread().getStackTrace();
   int I;
   for (I = 0; I < stack.length; I++) {
     if (stack[I].getClassName().equals("org.apache.log4j.Logger")) {
       break;
     }
   }
   return (getLogger(stack[I+1].getClassName()));
 }

This will use the stack to see what class it is inside of. Now all of my
classes can have the following:

private static Logger myLogger = Logger.getLogger();

No cut and paste errors.


StackTraceElement and the like were introduced in JDK 1.4 and log4j 1.x still targets JDK 1.3 and later. However, it could easily be incorporated in a utility function outside of the logging framework or in the extras companion which targets JDK 1.4 and later.




The other issue with log4j is with building parametrized debug messages. The documentation explains, correctly, that I should not do the following:

myLogger.debug("This is my debug value "+myObject);

This causes a StringBuffer to be built even though the call does not do anything when I'm not logging debug events. A simple solution would be to
have a parametrized debug method such as

public void debug(String msg, Object... params);

The implementation doesn't have to be fancy, maybe something similar to
MessageFormat.  This would let me pass the following:

myLogger.debug("This is my debug value {0}", myObject);

Now nothing is processed unless I'm logging debug events.



JDK 1.5 variable argument lists would still have the overhead of an invisible array creation. The LogMF and LogSF utility classes in the extras companion addresses that need and avoids unnecessary array creation and object boxing in most instances.

You could would now write:

LogMF.debug(myLogger, "This is my debug value {0}", myObject);

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to