Threading issues?? I knew someone would bring that up.  Thread safetyness is the responsibility, gladly accepted by a logger instance, not on the classes using it.  There is NO reason why we need paranoid checking here to only get one instance, since it is the responsibility of the logging implementation to even provide the instance in the first place.  Do you really think you'll get different instances?  Probably not, worst case scenario, you call Logger.getLogger() twice and initialize your instance twice in a race condition.  Since it is of zero consequence either way, there is no reason to do it differently.  If you are particularly worried, just do:

private transient Logger logger = LogFactory.getLogger(getClass());

You CANNOT use MyClass.class and have MySubClass.class show up in the log statements, since this is static.  You must use dynamic initialization.

-Kevin

Kevin A. Smith wrote:
That doesn't look thread-safe to me. You'd need to somehow synchronize access to getLogger() to eliminate a race-condition on the if(logger == null) test.
 
While its a bit more typing, I prefer:
 
private static Logger logger = LogFactory.getLogger(MyClass.class);
 
or
 
private static Logger logger = LogFactory.getLogger(MyClass.class.getName());
 
No threading issues and is pretty easy to read and understand.
 
--Kevin
-----Original Message-----
From: Kevin Ross [mailto:[EMAIL PROTECTED]]
Sent: Tuesday, November 19, 2002 2:18 PM
To: Vladimir R. Bossicard; [EMAIL PROTECTED]
Subject: Re: LogFactory.getLogger()

As I mentioned in my previous message, this is a poor way to obtain a logger, especially if you have deep inheritance heirarchies.  Since I'm a big fan of OO programming, and my heirarchies are especially deep, I find the static way of obtaining a logger invalid.

Try this:

public class AbstractLoggable{

    private static transient Logger logger;

    protected Logger getLogger(){

        if( logger == null ){

            logger = Logger.getLogger(getClass());  
        }

        return logger;
    }
}

whallah! efficient OO programming with an accessor for subclasses and the proper class name to go with it!

-Kevin Ross

Vladimir R. Bossicard wrote:
Logger.getLogger(getClass()) at least, whether or not you use the string
name is of no consequence.
    

have you ever tried to call a non-static method within a static reference?

if you get this working:

   private static Log log = LogFactory.getLog(getClass());

I give you a high-five.

-Vladimir

--
Vladimir R. Bossicard
www.bossicard.com

  


Reply via email to