views:

593

answers:

3

May I know what is the best practice of using org.apache.commons.logging.LogFactory.getLog?

For me, I use it the following way :

public class A
{
    private static final Log log = LogFactory.getLog(A.class);
}

public class B
{
    private static final Log log = LogFactory.getLog(B.class);
}

So, if I have 100 of classes, 100 of static log object will be created?

Or is it best to do it this way?

public class A
{
    private static final Log log = LogFactory.getLog(Main.class);
}

public class B
{
    private static final Log log = LogFactory.getLog(Main.class);
}

All the 100 classes are referring to a same single same log?

Thank you.

+2  A: 

The first option - have a logger per class (or functionality). As most logging systems - log4j, logback, java util logging, etc. have the notion of logger hierarchy, you can match that to your package hierarchy and have finer control of which functionality you want to be logged at which level. For example:

com.example=WARN       # global setting
com.example.web=INFO   # increase logging for the web controllers
com.example.dao=DEBUG  # trying to track bugs in the database layer
David Rabinowitz
+2  A: 

In the vast majority of cases, your way is the way to go.

The main advantage is that there is a logger (or category, or whatever) for each class that can be configured individually, like

log4j.logger.org.springframework.transaction=DEBUG

(assuming log4j) which will set the log level just for that class or package. If you use only one logger, you cannot do that.

Henning
A: 

Please remember the 'static problem', which most of java developer ignore and which affect log4j, java.util.Logger, and SLF4J as well. You can read about it in the Apache Commons Wiki[1]. As reported, if you're developing a library, planning to release it in a container (such as a j2ee container), shared among many application, is better use something like

private transient final Log logger = LogFactory.getLog( this.getClass() );
Matteo