如何使用 SLF4J 记录带有占位符的异常和消息
使用 SLF4J 记录错误消息和异常的正确方法是什么?
我尝试过这样做,但从未打印异常堆栈跟踪:
logger.error("Unable to parse data {}", inputMessage, e);
在这种情况下,我想填充 {}
与 inputMessage
以及注销异常堆栈跟踪。
我能想到的唯一方法是这样做:
logger.error("Unable to parse data " + inputMessage, e);
这并不漂亮。
What's the correct approach to log both an error message and an exception using SLF4J?
I've tried doing this but the exception stack trace is never printed:
logger.error("Unable to parse data {}", inputMessage, e);
In this case I want to populate {}
with the inputMessage
as well as logging out the exception stacktrace.
The only way I can see to do this would be to do this:
logger.error("Unable to parse data " + inputMessage, e);
which is not pretty.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 SLF4J 版本 1.6 开始,SLF4J 将按照您的预期解释最后一个参数,即作为例外。您必须使用旧版本的 SLF4J API。
此功能记录在 常见问题解答条目 中,该条目也在 Logger 的 javadocs。
As of SLF4J version 1.6, SLF4J will interpret the last parameter as you intended, i.e. as an exception. You must be using an older version of SLF4J API.
This feature is documented in a faq entry which is also referenced in the javadocs for Logger.
来自 http://www.slf4j.org/faq.html#paramException:
是,从 SLF4J 1.6.0 开始,但在以前的版本中没有。 SLF4J API 支持在出现异常时进行参数化,假设异常是最后一个参数。因此,
将按预期打印 NumberFormatException 及其堆栈跟踪。 java 编译器将调用带有 String 和两个 Object 参数的 error 方法。根据程序员最可能的意图,SLF4J 会将 NumberFormatException 实例解释为可抛出的对象,而不是未使用的 Object 参数。在 1.6.0 之前的 SLF4J 版本中,NumberFormatException 实例被简单地忽略。
如果异常不是最后一个参数,它将被视为普通对象,并且不会打印其堆栈跟踪。然而,这种情况在实际中不应该发生。
from 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. Thus,
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.