Some people really dislike debug log messages in production code. Though they can be extremely useful, I think a lot of developers are turned off to the fact that when logging is done poorly, it really makes the code look like a mess. For example, we’ve all seen code like this:

public class PressureValveController {
  public void closeValve() {
    logger.debug("my out temp" + temperature + " press: " + pressure + " and flowRate " + flowRate);
  }
}

The developer basically just dumped the stack to debug a specific problem they were having. This is one of a combination of factors that make code painful to read when logging is involved:

  • poor/no grammar
  • multiple log statements per method
  • excessive string concatenation

Sometimes, I like to create a helper method for logging in Java to make things more readable:

private void debug(String message, Object... args) {
  if(logger.isDebugEnabled()) {
    logger.debug(String.format(message, args));
  }
}

The next thing to do is to follow certain guidelines with respect to uniformity and sentence structure. For example:

public class PressureValveController {
  public void closeValve() {
    debug("Closing valve with output temperature: %d, pressure: %f PSI, and a flow of %f CFM.", temperature, pressure, flowRate);
  }
}

I think this ends up being a lot more useful in terms of code clarity and actual output. Loggers like slf4j and log4j2 can already do this out of the box and even provide support for deferred lambda expressions:

logger.trace("Some long-running operation returned {}", () -> expensiveOperation());