SLF4J Error Log Format

Variable s has string value. If I put that variable in Integer.valueOf method, I must encounter NumberFormatException. But It's not important. I just want to make exception.

Let's see the below code. I can log variable s and exception e together using logger format.

String s = "Hello world";
try {
  Integer i = Integer.valueOf(s);
} catch (NumberFormatException e) {
  logger.error("Failed to format {}", s, e);
}

However If I step insideerror method, I find that error method signature is weird. var3 argument is not Throwable type but Object type.

package org.slf4j;

public interface Logger {

  // var1 : "Failed to format {}"
  // var2 : s(String)
  // var3 : e(Exception)
  void error(String var1, Object var2, Object var3);

  ...
}

In the past, I revise my code like this for using error(String var1, Throwable var2)

log.error("this is error message : " + s, ex);
package org.slf4j;

public interface Logger {
  void error(String var1, Throwable var2);
}

We don't have to do that.

If there are exception in last parameter, SLF4J print stack trace and NumberFormatException automatically. SLF4J interprets it as Throwable, not Object, according to the developer's most likely intention.

cf) It's available from 1.6.0 version. If it is lower than 1.6.0, SLF4J ignore NumberFormatException.

Original Link: slf4j.org/faq.html#paramException