Best Practices on Logging

We list best practices on logging exceptions.

Log once

This is closely related with the Do not log and throw. You should try not to throw the same exception more than once. If you do not follow this rule your log file will be cluttered by outputs of the same exception incidence.

Log all in one Place

If there is information to be logged, log it with one call of the logger. If the information is split to more than one call, the information may be disrupted in the log file by log messages written by other threads.

Use Guards

Using guards to prevents runtime overhead. The message string is not required to be constructed if in the following example the log level is set to WARN.

if (log.isDebugEnabled()) {
  log.debug("No user found for ID '" + id + "' in context '" + context + "'.");
}

Default Log Level for Libraries

The default log level for libraries should be DEBUG. The application code is the only one to know if the result of a libraries calculation should be deemed as FATAL, ERROR, WARN, or INFO. So these higher level log levels are reserved for application code.