Anatoly Yakimchuk Anatoly Yakimchuk - 1 year ago 72
Java Question

log4j with checks prior to actual logging

I'm trying to learn the log4j2 library and in the tutorials they write logging with checks like this:

if (logger.isErrorEnabled()) {
logger.error("some information");

But I can't find what is the point of this check? Can I omit it and write just

logger.error("some information");


Answer Source

The point is usually performance. For the simple case you've shared, these checks are indeed mostly redundant, and only serve to follow convention with the rest of the places where they aren't (as described in the following paragraph).

Consider, however, a case where your messages isn't as simple. E.g., it contains expensive toString() or string formatting calls:

log.debug("some error occurred: " + generateExpensiveLogMessage());

You may be wasting valuable resources in generating this method just to find that it will never be printed as your logging is configured to omit this level. In this case, the check will enable you to save these redundant calculations:

if (log.isDebugEnabled()) {
    // Expensive method only called if we know we're actually going to log it
    log.debug("some error occurred: " + generateExpensiveLogMessage());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download