logging-log4j-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Brian Hawkins <brianh...@gmail.com>
Subject A default getLogger method
Date Mon, 26 Jan 2009 22:27:11 GMT
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:

  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")) {
    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.

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.



  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message