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?
one instance of Logger per class e.g.
class Foo { private static final Logger log = Logger.getLogger(Foo.class); }
Note: This issue is already considered to some extent in these articles:
Whats the overhead of creating a Log4j Logger
log4j has three main components: loggers: Responsible for capturing logging information. appenders: Responsible for publishing logging information to various preferred destinations. layouts: Responsible for formatting logging information in different styles.
Log4j allows logged messages to contain format strings that reference external information through the Java Naming and Directory Interface (JNDI). This allows information to be remotely retrieved across a variety of protocols, including the Lightweight Directory Access Protocol (LDAP).
Typically, you'd have loggers setup per class because that's a nice logical component. Threads are already part of the log messages (if your filter displays them) so slicing loggers that way is probably redundant.
Regarding application or layer based loggers, the problem is that you have to find a place to stick that Logger object. Not a really big deal. The bigger issue is that some classes may be used at multiple levels of from multiple applications... it could be difficult to get your logger right. Or at least tricky.
...and the last thing you want is bad assumptions in your logging setup.
If you care about applications and layers and have easy separation points, the NDC is the way to go. The code can be a little excessive sometimes but I don't know how many times I've been saved by an accurate context stack showing me that Foo.bar() was called from application X in layer Y.
The strategy that is most used is to create a logger per class. If you create new threads give them a usefull name, so their logging is easily distinguishable.
Creating loggers per class has the benefit of being able to switch on/off logging in the package structure of your classes:
log4j.logger.org.apache = INFO log4j.logger.com.example = DEBUG log4j.logger.com.example.verbose = ERROR
The above would set all apache library code to INFO
level, switch logging from your own code to DEBUG
level with the exception of the verbose package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With