I've been using log4j and log4net as my logging facility for some time now, and haven't thought a lot about it. I did today though... I had a junit test with some mock objects that were getting used only if debug logging was enabled. Do I know the developer running the test has debug logging enabled? The answer is, the unit test shouldn't care, but how do I get around this in my unit test?
The real issue I was having was that in my class under test I was doing things like log.isDebugEnabled() to avoid a bunch of string concatentation in my logging. Apparenlty there's a better way to avoid the string concatentation penality and also provides cleaner syntax IMO.
As of log4j version 1.3, there exists a significantly more
convenient alternative based on message patterns. Assuming
entry is an object, you can write:
l.debug("The new entry is {}.", entry);
After evaluting whether to log or not, and only if the
decision is positive, will the logger instace format the
message and replace the '{}' pair with the string value of
entry. In other words, the paramerized form does
not incur the cost of parameter construction in case the log
statement is disabled.
Thus, the following two lines will yield the exact same
output. However, the second form will perform at least 30
(thirty) times faster in case of a disabled logging
statement.
l.debug("The new entry is "+entry+".");
l.debug("The new entry is {}.", entry);
A two argument variant is also availalble. For example, you
can write:
l.debug("The new entry is {}. It replaces {}.", entry, oldEntry);