Home > Software design >  Why does a logger Java need check isDebugEnabled()?
Why does a logger Java need check isDebugEnabled()?

Time:02-17

Why java logger need check

if (log.isDebugEnabled()) {
   log.debug("Debug message");
}

instead call directly log.debug("Debug message");?

CodePudding user response:

It doesn't. Typically, you would call log.isDebugEnabled() in cases when you need some extra code to log what you want:

if (log.isDebugEnabled()) {
    for (...) {
        // Some heavy logic that is only needed when logging things
        log.debug("Debug message");
    }
}

This way you never trigger the extra logic when it's not needed.

CodePudding user response:

In addition to @1615903's answer:

You can configure different levels of logging. For some environment you might want to disable DEBUG level and logging engine (SLF4J) wouldn't put those messages into log but the code (log.debug("...")) would still be executed, which is completely useless with disabled DEBUG level. Using isXXXEnabled() you can avoid excess work.

  • Related