log4j打印抛出异常时堆栈内容

JAVA 中为快速定位,抛出异常的位置。往往需要在日志中描述。
【log4j打印抛出异常时堆栈内容】log.err("异常出错点", e); 会将出错时的堆栈信息显示出来。

package com.jqyc.jase; import static org.junit.Assert.*; import org.apache.log4j.Logger; import org.junit.Test; public class TestError { Logger log = Logger.getLogger(TestError.class); @Test public void test() { String s = null; try { s.length(); } catch (Exception e) { log.error( "出错日志"+s, e); // 当然如果你懒得想提示信息的话,直接这样log.error("", e); System.out.println(e.getMessage()); } }}

[com.jqyc.jase.TestError.test(TestError.java:18)] - 出错日志null java.lang.NullPointerException at com.jqyc.jase.TestError.test(TestError.java:16) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)


  • printStackTrace()方法的意思是:在命令行打印异常信息在程序中出错的位置及原因。但只会在标准输出stdout 与stderr中进行输出,无法将内容输出到日志。
  • 需要日志中进行输出,直接打印e对象。

参考:http://codepub.cn/2016/04/15/Log4j-print-exception-stack-information-to-the-log/


    推荐阅读