slf4j如何打印java异常堆栈信息throwable对象

SLF4J 1.6.0 以前的版本,如果打印异常堆栈信息,必须用

log.error(String msg, Throwable t)

log.info等对应方法.

如果msg含有变量,一般用String.format方法格式化msg.

如果用

error(String format, Object... arguments)

等其它方法,异常堆栈信息会丢失.

幸好,SLF4J 1.6.0以后的版本对这个不友好的异常信息log 改进了.

error(String format, Object... arguments) 这个方法也会打印异常堆栈信息,只不过规定throwable对象必须为

最后一个参数.如果不遵守这个规定,异常堆栈信息不会log出来.

官方FAQ:http://www.slf4j.org/faq.html

Can I log an exception without an accompanying message?

In short, no.

If e is an Exception, and you would like to log an exception at the ERROR level, you must add an accompanying message. For example,

logger.error("some accompanying message", e);

You might legitimately argue that not all exceptions have a meaningful message to accompany them. Moreover, a good exception should already contain a self explanatory description. The accompanying message may therefore be considered
redundant.

While these are valid arguments, there are three opposing arguments also worth considering. First, on many, albeit not all occasions, the accompanying message can convey useful information nicely complementing the description contained
in the exception. Frequently, at the point where the exception is logged, the developer has access to more contextual information than at the point where the exception is thrown. Second, it is not difficult to imagine more or less generic messages, e.g. "Exception
caught", "Exception follows", that can be used as the first argument for error(String msg, Throwable t) invocations. Third, most log output formats display the message on a line, followed by the exception
on a separate line. Thus, the message line would look inconsistent without a message.

In short, if the user were allowed to log an exception without an accompanying message, it would be the job of the logging system to invent a message. This is actually what the throwing(String
sourceClass, String sourceMethod, Throwable thrown)
method in java.util.logging package does. (It decides on its own that accompanying message is the string "THROW".)

It may initially appear strange to require an accompanying message to log an exception. Nevertheless, this is common practice in all log4j derived systems such as java.util.logging, logkit, etc. and of course log4j itself.
It seems that the current consensus considers requiring an accompanying message as a good a thing (TM).

In the presence of an exception/throwable, is it possible to parameterize a logging statement?

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.

时间: 2024-10-19 22:16:01

slf4j如何打印java异常堆栈信息throwable对象的相关文章

Java异常堆栈信息转String

平时使用e.getMessage()或e.printStackTrace(); 第一种报异常时要throw new RuntimeException("异常"),只能得到异常2字. 第二种e.printStackTrace();只是打印,不返回任何数据. 而服务器一般是集群或其他方式部署,查看日志的话太麻烦,可以吧堆栈信息转成String等类型,然后进行保存到数据库.放在页面隐藏域中方便查看. 介绍3种方法供选择: 方法一: package name.xu;public class C

日志如何打印异常堆栈信息。

package com.doctor.slf4j; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 如何打印异常堆栈信息. * @author doctor * * @time 2014年12月11日 上午9:49:00 */ public class LogThrowableRule { private final Logger log = LoggerFactory.g

异常堆栈信息输出工具类

public class MyExceptionUtils { /** * 输入异常的堆栈信息 * @param aThrowable * @return */ public static String getStackTrace(Throwable e) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(pr

SpringBoot-技术专区-详细打印启动时异常堆栈信息

SpringBoot在项目启动时如果遇到异常并不能友好的打印出具体的堆栈错误信息,我们只能查看到简单的错误消息,以致于并不能及时解决发生的问题,针对这个问题SpringBoot提供了故障分析仪的概念(failure-analyzer),内部根据不同类型的异常提供了一些实现,我们如果想自定义该怎么去做? FailureAnalyzer SpringBoot提供了启动异常分析接口FailureAnalyzer,该接口位于org.springframework.boot.diagnosticspack

Java获取异常堆栈信息

public String getExceptionStack(Exception e){ StackTraceElement[] stackTraceElements = e.getStackTrace(); String prefix = "Exception in thread "+"\""+Thread.currentThread().getName()+"\" "; String result = prefix+e.

02. 将异常堆栈信息,返回给前台,便于排查问题.

需求: 我们在排查线上可复现问题时,如果出现异常可能还需要登陆服务器去翻日志. 解决: java Code @RequestMapping("UserController/register") @ResponseBody public Map<Object, Object> register(String email, String userName, String password) { HashMap<Object, Object> result = Met

将异常堆栈信息转换成字符串

package cn.com.aia.grouplife.utils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; public class ExceptionMsgUtils { /** * getExceptionInfo * @param e * @return result限

Java异常的深入研究与分析

对于本文的内容,属于基础知识研究范畴,切勿以为读完此文就能将异常知识掌握到家.切记:操千曲而后晓声,观千剑而后识器,所以我觉得没有大量的源码阅读经验,你很难知道什么时候需要自定义异常,什么时候需要抛出异常. 异常机制概述 异常机制是指当程序出现错误后,程序如何处理.具体来说,异常机制提供了程序退出的安全通道.当出现错误后,程序执行的流程发生改变,程序的控制权转移到异常处理器. 异常处理的流程 当程序中抛出一个异常后,程序从程序中导致异常的代码处跳出,java虚拟机检测寻找和try关键字匹配的处理

java异常——RuntimeException和User Define Exception

1.RuntimeException public class RuntimeException { public static void main(String[] args) { // TODO Auto-generated method stub String str="123"; int temp=Integer.parseInt(str); System.out.println(temp*temp); } } 查看parseInt方法的源代码如下: public static