You Are Logging All Wrong – Hacker Noon

This is an example of some code that logs messages the wrong way:

List veryLongList = …
// explicit invoke object's toString()
logger.debug(“my long list is “ + veryLongList.toString());
logger.debug(“my extra long list is %s”, veryLongList.toString());
// implicit invoke object's toString()
logger.debug(“my long list is “ + veryLongList);

All three of these versions are inefficient and error prone and should be avoided.

The reason is the call to toString(). it forces the creation of a possibly expensive String object that is then passed to the LogWrapper.debug() method.

To understand the problem with this, look at how the debug method is implemented:

public void debug(Object message) {
if (ThreadedLogLevelManager.isDebugEnabled(m_logger)) {
m_logger.log(s_className, Level.DEBUG, message, null);
public void debug(Object message, Object arg) {
if (ThreadedLogLevelManager.isDebugEnabled(m_logger)) {
m_logger.log(s_className, Level.DEBUG, message, arg);
public void debug(Object message, Object... args) {
if (ThreadedLogLevelManager.isDebugEnabled(m_logger)) {
m_logger.log(s_className, Level.DEBUG, message, args);

You can see that we first check and see the debug mode is enabled for this piece of code and only then goes to call the m_logger that does the logging.

Usually the m_logger won’t even be called since debug logging is generally disabled in production.

The m_logger itself then goes and turn the message into a string.
You can see below that the way it converts it into string is also an important check that we as developers sometime forget to do:

protected final String convertToString(Object message) {
return message == null ? (String)message : message.toString();

This protects you from getting a NullPointerException.

read original article here