I decided to use Log4J logging framework for a new Java project. I am wondering what strategy should I use for creating/managing Logger instances and why?
As has been said by others, I would create a Logger per class:
private final static Logger LOGGER = Logger.getLogger(Foo.class);
or
private final Logger logger = Logger.getLogger(this.getClass());
However, I have found it useful in the past to have other information in the logger. For instance, if you have a web site, you could include the user ID in every log message. That way,, you can trace everything a user is doing (very useful for debugging problems etc).
The easiest way to do this is to use an MDC, but you can use a Logger created for each instance of the class with the name including the user ID.
Another advantage of using an MDC is if you use SL4J, you can change the settings depending upon the values in your MDC. So if you wish to log all activity for a particular user at DEBUG level, and leave all of the other users at ERROR, you can. You can also redirect different output to different places depending upon your MDC.
Some useful links:
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/MDC.html
http://www.slf4j.org/api/index.html?org/slf4j/MDC.html