记录器格式和 throwable、slf4j、参数

Logger format and throwable, slf4j, arguments

在将一些旧记录器从 String.format 转换为较新的 slf4j {} 变体的过程中,我偶然发现了这种情况:

logger.error(String.format("%s ... %s ... %s", ...), e);

我只想使用 {} 并删除字符串格式,但是, 包含 throwable 的记录器方法签名是:

error(String msg, Throwable t)

所以在这种情况下我必须保留 String.format?!

为什么没有:

error(Throwable t, String format, Object... arguments)

从 SLF4J 1.6.0 开始,在存在多个参数的情况下,如果日志语句中的最后一个参数是异常,则 SLF4J 将假定用户希望将最后一个参数视为异常,而不是一个简单的参数。

因此,编写(在 SLF4J 版本 1.6.x 及更高版本中)

logger.error("one two three: {} {} {}", "a", "b", 
          "c", new Exception("something went wrong"));

http://www.slf4j.org/faq.html#paramException:

"Yes, as of SLF4J 1.6.0, but not in previous versions. The SLF4J API supports parametrization in the presence of an exception, assuming the exception is the last parameter."