Quote dynamic text when logging

Extraneous leading or trailing whitespace around text is easy to add and difficult to detect - a bad combination. If text has some logical meaning to the program (for example, the name of a configuration parameter), then extraneous whitespace around it is almost always undesired.

(This problem occurs for text data, but not for numeric data such as BigDecimal or Integer.)

To help detect such unwanted whitespace, simply quote dynamic text values when logging. It's likely a good idea to define a simple utility method for this purpose.

Example

This example uses Objects.toString(Object). That method has the advantage of being null-friendly.

import java.util.Objects;

public final class Util {

  /**
  * Surround the result of <tt>Objects.toString(aObject)</tt> with single quotes.
  */
  public static String quote(Object object){
    return "'" + Objects.toString(object) + "'";
  }

} 

See Also :
Logging messages