logging-log4j-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Douglas E Wegscheid <Douglas_E_Wegsch...@whirlpool.com>
Subject Re: A default getLogger method
Date Wed, 28 Jan 2009 13:34:23 GMT
a good point, but the Brian (the original poster) was looking for a way to 
avoid having to provide the Class object when calling 
Logger.getLogger(Class clazz). He was suggesting a way to provide a 
no-args Logger.getLogger(). Having a no-args Logger.getLogger() would be 
really nice, but using the stack trace to determine the caller's class has 
a few limitations (doesn't work correctly in some inheritance situations, 
stack traces may not be complete with some JVMs, no pre 1.4 
implementation).

if Brian is comfortable with those limitations/risks, he can use the code 
he wrote to do what he wants without modifying log4j itself. *I'm* 
comfortable with it for my stuff, and it's part of my bag o'tricks....

package org.wegscheid.log4j;

import org.apache.log4j.Logger;

public class MyMagicLogFactory {
  public static Logger getLogger() {
    String myClassName = MyMagicLogFactory.class.getName();
 
    StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    //stack = new Throwable().getStackTrace();
 
    for (int i = 0; i < stack.length; i++) {
      if (myClassName.equals(stack[i].getClassName())) {
        return Logger.getLogger(stack[i+1].getClassName());
      }
    }
    return null;
  }
}

package org.wegscheid.traceback;

import org.apache.log4j.Logger;
import org.wegscheid.log4j.MyMagicLogFactory;

public class Thing {
  static Logger logger = MyMagicLogFactory.getLogger();
  public static void main (String[] args) {
    logger.info("it's magic...");
  }
}

while I'm willing to personally live with the risk for personal projects, 
I'd be nervous about making this part of log4j and forcing/encouraging 
some new log4j user to live with it, it's just not reliable...

I hadn't seen the Thread.currentThread().getStackTrace() show up in Java5 
(I've been using the StackTraceElement[] stack = new 
Throwable().getStackTrace(); hack), and appreciate him sharing his idea.\

Douglas E Wegscheid
Lead Technical Analyst, Whirlpool Corporation
(269)-923-5278

"A wrong note played hesitatingly is a wrong note. A wrong note played 
with conviction is interpretation."


> "Craig P. Motlin" <motlin@gmail.com> wrote:
>This is a non-issue.  If you need to log an object's type, call
>getClass().getName() and log it as a normal message.  Stick to one
>private static logger in each class.  The logger name will represent
>where the logging statement occurred, not the run time type of the
>logging object.



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