今天和同事讨论一个问题,log.error("eee{}","11111",e); 能否打印出异常堆栈的问题,在我的印象里,
org.slf4j.Logger 类里的error的重载的方法里面只有2个参数的,最后一个参数为Throwable类型的入参 (标红颜色的),其他都为第一个模板参数format的动态参数
/**
* Log a message at the ERROR level.
*
* @param msg the message string to be logged
*/
public void error(String msg);
/**
* Log a message at the ERROR level according to the specified format
* and argument.
* <p/>
* <p>This form avoids superfluous object creation when the logger
* is disabled for the ERROR level. </p>
*
* @param format the format string
* @param arg the argument
*/
public void error(String format, Object arg);
/**
* Log a message at the ERROR level according to the specified format
* and arguments.
* <p/>
* <p>This form avoids superfluous object creation when the logger
* is disabled for the ERROR level. </p>
*
* @param format the format string
* @param arg1 the first argument
* @param arg2 the second argument
*/
public void error(String format, Object arg1, Object arg2);
/**
* Log a message at the ERROR level according to the specified format
* and arguments.
* <p/>
* <p>This form avoids superfluous string concatenation when the logger
* is disabled for the ERROR level. However, this variant incurs the hidden
* (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
* even if this logger is disabled for ERROR. The variants taking
* {@link #error(String, Object) one} and {@link #error(String, Object, Object) two}
* arguments exist solely in order to avoid this hidden cost.</p>
*
* @param format the format string
* @param arguments a list of 3 or more arguments
*/
public void error(String format, Object... arguments);
/**
* Log an exception (throwable) at the ERROR level with an
* accompanying message.
*
* @param msg the message accompanying the exception
* @param t the exception (throwable) to log
*/
public void error(String msg, Throwable t);
但是同事坚持log.error("eee{}","11111",e); 这样也能打出异常堆栈,感觉不合常理,本地验证下
public static void main(String[] args) { try{ int i = 1/0; }catch (Exception e){ log.error("eee{}","11111",e); } }
输出结果:
15:25:34.462 [main] ERROR com.credithc.inner.InnerApplication - eee11111
java.lang.ArithmeticException: / by zero
at com.credithc.inner.InnerApplication.main(InnerApplication.java:31)
确实打印出了,异常堆栈, 很是不解,遂debug下
在logback的实现里面有个特殊的处理
会判断下最后一个参数(注意只在最后)是否是Throwable对象,如果是 ,就打印异常堆栈。