java 使用可变参数方法的 SLF4J 参数化日志记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17716381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SLF4J parameterized logging using varargs method
提问by Manjabes
I must be stupid or something, but I seem not to be able to use the varargs-utilizingparameterized logging methods of SLF4J. An example:
我一定是愚蠢或什么,但我似乎无法使用SLF4J 的使用可变参数的参数化日志记录方法。一个例子:
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);
}
}
}
On the logging method, eclipse produces such a warning:
在日志记录方法上,eclipse 会产生这样的警告:
The method error(String, Object, Object) in the type Logger is not applicable for the arguments (String, int, long, int, Exception)
and fails to compile.
并且无法编译。
However, if I change the logging call to:
但是,如果我将日志记录调用更改为:
logger.error("I wanna log {} and {} and {} with backtrace", new Object[]{x, y, 3, e});
It compiles and runs as expected (logging 3 "variables" and the exception stack trace).
它按预期编译和运行(记录 3 个“变量”和异常堆栈跟踪)。
The library versions are: slf4j-api-1.7.5.jar, slf4j-log4j12-1.7.5.jar and log4j-1.2.14.jar, if it makes any difference.
库版本是:slf4j-api-1.7.5.jar、slf4j-log4j12-1.7.5.jar 和 log4j-1.2.14.jar,如果有什么不同的话。
If anybody would point out the shortcomings of my thinking abilities, it'd be very much appreciated!
如果有人指出我的思维能力的不足,将不胜感激!
回答by ZachOfAllTrades
I did some additional investigation, and the only way to get a compile error for
我做了一些额外的调查,这是获得编译错误的唯一方法
logger.error("I wanna log {} and {} and {} with backtrace", x, y, 3, e);
and not for
而不是为了
logger.error("I wanna log {} and {} and {} with backtrace", new Object[]{x, y, 3, e});
is to use a version of the SLF4J API prior to 1.7 (in which support for varargs was introduced). You probably need to dig into your classpath (or server runtime?) to find where the following statement fails to be true:
是使用 1.7 之前的 SLF4J API 版本(其中引入了对可变参数的支持)。您可能需要深入研究类路径(或服务器运行时?)以找出以下语句不正确的地方:
The library versions are: slf4j-api-1.7.5.jar, slf4j-log4j12-1.7.5.jar and log4j-1.2.14.jar, if it makes any difference.
库版本是:slf4j-api-1.7.5.jar、slf4j-log4j12-1.7.5.jar 和 log4j-1.2.14.jar,如果有什么不同的话。
(because it certainly makes precisely the difference that you have observed)
(因为它确实使您观察到的差异完全不同)