Re: log4j methods: instance or class?
On Thu, 21 Jun 2007 21:07:29 +0200, Charles T. Smith wrote:
The javadocs for getLogger() says
If the named logger already exists, then the existing instance will be
returned. Otherwise, a new instance is created.
Another words, it's an instance (non-static) method.
An example program I have (using the old interface) is:
static Category log = Category.getInstance(Css.class.getName());
It's stored in a static variable.
Is this wrong?
If it's not wrong, does that mean that all threads share the same
reference? If they do, does that mean that log4j automatically sequences
access?
Okay, I've learned a little bit more. I ran the following test program
and realized that you can create the logger either way, with slightly
different semantics, depending.
The question remains: if statically declared, does the logger do its own
sequencing, or is the user headed for trouble in a threaded environment?
import org.apache.log4j.Category;
class log4j {
// either (seem to) work for both static and non-static callers.
//
// No.
// With static, it can be called from main() or sub.
// Without static it can only be called from sub.
static Category log = Category.getInstance(log4j.class.getName());
// Category log = Category.getInstance(log4j.class.getName());
// Note that 'int count' can't be referenced from (static) main()
// but 'static int count' *can* be referenced from (non-static) sub()
// int count = 0;
static int count = 0;
public static void main (String[] args)
{
log4j logger = new log4j ();
// note that you can call log.debug only when it's declared to be static
log.debug("main: entered");
System.out.println ("hello world");
logger.sub();
// you can call logger.log.debug whether it's static or not
logger.log.debug ("main: " + count);
}
public void sub ()
{
log.debug("sub: entered");
count++;
}
}