SLF4J使用varargs方法参数化日志记录

Man*_*bes 15 java slf4j

我必须是愚蠢的东西,但我似乎无法使用SLF4J 的varargs利用参数化日志记录方法.一个例子:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingTest {

    @Test
    public void loggingTest() {
        Logger logger = LoggerFactory.getLogger(this.getClass());
        int x = 0xdeadbeef;
        long y = 0xdeadbeef;

        try {
            throw new Exception("This is a mighty exception!");
        } catch(Exception e) {
            logger.error("I wanna log {} and {} and {} with backtrace", x, y, 3, e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在日志记录方法上,eclipse产生了这样一个警告:

The method error(String, Object, Object) in the type Logger is not applicable for the arguments (String, int, long, int, Exception)
Run Code Online (Sandbox Code Playgroud)

并且无法编译.

但是,如果我将日志记录调用更改为:

logger.error("I wanna log {} and {} and {} with backtrace", new Object[]{x, y, 3, e});
Run Code Online (Sandbox Code Playgroud)

它按预期编译和运行(记录3个"变量"和异常堆栈跟踪).

库版本是:slf4j-api-1.7.5.jar,slf4j-log4j12-1.7.5.jar和log4j-1.2.14.jar,如果它有任何区别.

如果有人指出我的思维能力的缺点,我将非常感激!

Zac*_*des 26

我做了一些额外的调查,并且是获得编译错误的唯一方法

logger.error("I wanna log {} and {} and {} with backtrace", x, y, 3, e);
Run Code Online (Sandbox Code Playgroud)

而不是

logger.error("I wanna log {} and {} and {} with backtrace", new Object[]{x, y, 3, e});
Run Code Online (Sandbox Code Playgroud)

是在1.7之前使用SLF4J API的一个版本(其中引入了对varargs的支持).您可能需要深入了解类路径(或服务器运行时?)以查找以下语句无效的位置:

库版本是:slf4j-api-1.7.5.jar,slf4j-log4j12-1.7.5.jar和log4j-1.2.14.jar,如果它有任何区别.

(因为它肯定会使你观察到的差别正是如此)