可以使用java.util.logging工具将输出记录在日志中。记录日志的的功能还是很简单的,下面直接铺出代码:
1 package com.exceptions; 2 3 import java.io.*; 4 import java.util.logging.Logger; 5 6 class LoggingException extends Exception{ 7 private static Logger logger = 8 Logger.getLogger("LoggeringException"); 9 public LoggingException(){ 10 StringWriter trace = new StringWriter(); 11 printStackTrace(new PrintWriter(trace)); 12 logger.severe(trace.toString()); 13 } 14 } 15 16 public class LoggingExceptions { 17 public static void main(String [] args) 18 { 19 try{ 20 throw new LoggingException(); 21 }catch(LoggingException e){ 22 System.err.println("Caught"+ e); 23 } 24 try{ 25 throw new LoggingException(); 26 }catch(LoggingException e){ 27 System.out.println("Caught"+ e); 28 } 29 } 30 }
结果:
1 六月 22, 2014 9:32:41 下午 com.exceptions.LoggingException <init> 2 严重: com.exceptions.LoggingException 3 at com.exceptions.LoggingExceptions.main(LoggingExceptions.java:20) 4 5 Caughtcom.exceptions.LoggingException 6 六月 22, 2014 9:32:41 下午 com.exceptions.LoggingException <init> 7 严重: com.exceptions.LoggingException 8 at com.exceptions.LoggingExceptions.main(LoggingExceptions.java:25) 9 10 Caughtcom.exceptions.LoggingException
尽管LoggingException将所有日志的基础设施都构建在异常自身中,使得它所使用的方式非常方便,并因此不需要客户端程序员的干预就可以自动运行,但是更常见的情形是我们需要捕获和记录其他人编写的异常,因此我们必须在异常处理程序中生成日志消息:
1 /** 2 * 3 */ 4 package com.exceptions; 5 6 import java.util.logging.Logger; 7 import java.io.*; 8 9 public class LoggingExceptions2 { 10 11 /** 12 * @param args 13 */ 14 private static Logger logger = 15 Logger.getLogger("LoggingExceptions"); 16 static void logException(Exception e){ 17 StringWriter trace = new StringWriter(); 18 e.printStackTrace(new PrintWriter(trace)); 19 logger.severe(trace.toString()); 20 } 21 public static void main(String[] args) { 22 // TODO Auto-generated method stub 23 try{ 24 throw new NullPointerException(); 25 }catch(NullPointerException e){ 26 logException(e); 27 } 28 } 29 30 }
结果:
六月 22, 2014 9:47:03 下午 com.exceptions.LoggingExceptions2 logException
严重: java.lang.NullPointerException
at com.exceptions.LoggingExceptions2.main(LoggingExceptions2.java:24)