gpt4 book ai didi

java - 为什么 slf4j 的 Logger 没有一个方法可以同时接受消息的可变参数和异常?

转载 作者:行者123 更新时间:2023-12-01 14:07:56 32 4
gpt4 key购买 nike

SLF4J's Logger具有接受异常或 varargs 的日志记录方法但不是两者兼而有之。

知道为什么吗?

缺少签名的问题是,有时我想记录异常并为消息提供参数,但我没有方法签名来做这两件事。

最佳答案

引用 In the presence of an exception/throwable, is it possible to parameterize a logging statement? ,你可以从 SLF4J 1.6.0 开始这样做,如果异常是最后一个参数:

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. Thus,

String s = "Hello world";

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

will print the NumberFormatException with its stack trace as expected. The java compiler will invoke the error method taking a String and two Object arguments. SLF4J, in accordance with the programmer's most probable intention, will interpret NumberFormatException instance as a throwable instead of an unused Object parameter. In SLF4J versions prior to 1.6.0, the NumberFormatException instance was simply ignored.

If the exception is not the last argument, it will be treated as a plain object and its stack trace will NOT be printed. However, such situations should not occur in practice.

作为一个示例实现,这是由 Logback 调用的方法(该方法在类 ch.qos.logback.classic.spi.EventArgUtil 和被 ch.qos.logback.classic.spi.LoggingEvent 调用):

public static final Throwable extractThrowable(Object[] argArray) {
if (argArray == null || argArray.length == 0) {
return null;
}

final Object lastEntry = argArray[argArray.length - 1];
if (lastEntry instanceof Throwable) {
return (Throwable) lastEntry;
}
return null;
}

关于java - 为什么 slf4j 的 Logger 没有一个方法可以同时接受消息的可变参数和异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50016351/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com