可以使用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)
?
?