用logger 输出printStackTrace() log4jException
程序员文章站
2022-07-15 09:20:39
...
public class HelloLog4jChild extends HelloLog4j { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub logger.debug("This is debug message!"); logger.info("This is info message!"); logger.error("This is error message!"); HelloLog4jChild object = new HelloLog4jChild(); try { object.testMethod(); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); logger.error("HelloLog4jException", e); } } public void testMethod() throws Exception { try { testMethod2(); } catch (Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); throw new ClassNotFoundException("test1 Exception", e); } } public void testMethod2() throws Exception { throw new ClassNotFoundException("test2 Exception"); } }
使用logger.error("ExceptionName",e),可以很轻松的将printStackTrace()输出到log文件中(printStackTrace()是将错误的堆栈信息输出到Console中)。
引用
[11/07/27 13:18:58:812][com.zsk.log4j.demo1.HelloLog4jChild-main] This is info message!
[11/07/27 13:18:58:828][com.zsk.log4j.demo1.HelloLog4jChild-main] This is error message!
[11/07/27 13:18:58:828][com.zsk.log4j.demo1.HelloLog4jChild-main] HelloLog4jException
java.lang.ClassNotFoundException: test1 Exception
at com.zsk.log4j.demo1.HelloLog4jChild.testMethod(HelloLog4jChild.java:29)
at com.zsk.log4j.demo1.HelloLog4jChild.main(HelloLog4jChild.java:15)
Caused by:
java.lang.ClassNotFoundException: test2 Exception
at com.zsk.log4j.demo1.HelloLog4jChild.testMethod2(HelloLog4jChild.java:36)
at com.zsk.log4j.demo1.HelloLog4jChild.testMethod(HelloLog4jChild.java:25)
... 1 more
[11/07/27 13:18:58:828][com.zsk.log4j.demo1.HelloLog4jChild-main] This is error message!
[11/07/27 13:18:58:828][com.zsk.log4j.demo1.HelloLog4jChild-main] HelloLog4jException
java.lang.ClassNotFoundException: test1 Exception
at com.zsk.log4j.demo1.HelloLog4jChild.testMethod(HelloLog4jChild.java:29)
at com.zsk.log4j.demo1.HelloLog4jChild.main(HelloLog4jChild.java:15)
Caused by:
java.lang.ClassNotFoundException: test2 Exception
at com.zsk.log4j.demo1.HelloLog4jChild.testMethod2(HelloLog4jChild.java:36)
at com.zsk.log4j.demo1.HelloLog4jChild.testMethod(HelloLog4jChild.java:25)
... 1 more
注意Caused by:是不同层级的Exception所产生的
throw new ClassNotFoundException("test1 Exception", e);
上一篇: 深度剖析c语言main函数---main函数的参数传递
下一篇: xml+css显示数据