Best practice using org.apache.commons.logging.LogFactory.getLog

Can I find out what is the best practice for using org.apache.commons.logging.LogFactory.getLog?

For me, I use it as follows:

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 classes, will 100 static log objects be created?

Or is it better 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); } 

Do all 100 classes belong to the same journal?

Thanks.

+4
source share
3 answers

The first option is to have a registrar for each class (or functionality). Since most logging systems are log4j, logback, java util logging, etc. Having the concept of a log hierarchy, you can correlate this with your package hierarchy and have finer control over which functions you want to register at which level. For instance:

 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 
+3
source

Remember the “static problem” that most Java developers ignore and that affect log4j, java.util.Logger, and SLF4J. You can read about it in the Apache Commons Wiki . As reported, if you are developing a library planning to release it in a container (for example, in a j2ee container) that is shared with many applications, it’s better to use something like

 private transient final Log logger = LogFactory.getLog( this.getClass() ); 
+4
source

In the vast majority of cases, your path is the path.

The main advantage is that for each class that can be configured individually, there is a journal (or category or something else), for example

 log4j.logger.org.springframework.transaction=DEBUG 

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

+2
source

All Articles