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中)。
[quote][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[/quote]
注意Caused by:是不同层级的Exception所产生的
throw new ClassNotFoundException("test1 Exception", e);
本文介绍了一种利用Log4j框架记录Java程序异常的方法,通过示例代码展示了如何使用logger.error方法捕获并记录异常堆栈信息至日志文件,有效替代传统的printStackTrace输出方式。
924

被折叠的 条评论
为什么被折叠?



