1. 程式人生 > >使用Spring進行統一日誌管理 + 統一異常管理

使用Spring進行統一日誌管理 + 統一異常管理

統一日誌和異常管理配置好後,SSH專案中程式碼以往散落的log.info() 和 try..catch..finally 再也不見蹤影,統一日誌異常實現類。

1,統一日誌處理實現類

package net.xnzz.util;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;

/**
 * Spring 統一日誌處理實現類
 * @author WANGJIE
 *
 */
public class LogInterceptor implements MethodInterceptor 
{
	public Object invoke(MethodInvocation invocation) throws Throwable   
	{   
	    Logger loger = Logger.getLogger(invocation.getClass());   
	    loger.info("--Log By Andy Chan -----------------------------------------------------------------------------");   
	    loger.info(invocation.getMethod() + ":BEGIN!--(Andy ChanLOG)");//方法前的操作    
	    Object obj = invocation.proceed();// 執行需要Log的方法    
	    loger.info(invocation.getMethod() + ":END!--(Andy ChanLOG)");//方法後的操作    
	    loger.info("-------------------------------------------------------------------------------------------------");   
	    return obj;   
	}
}
2,自定義業務異常處理類
package net.xnzz.util;
/**
 * 自定義業務異常處理類    友好提示  
 * @author WANGJIE
 *
 */
public class BusinessException extends RuntimeException 
{
	private static final long serialVersionUID = 3152616724785436891L;   

	     public BusinessException(String frdMessage)   

	     {   
	         super(createFriendlyErrMsg(frdMessage));   
	     }   
	     public BusinessException(Throwable throwable)   
	     {   
	         super(throwable);   
	     }   
	     public BusinessException(Throwable throwable, String frdMessage)   
	     {   
	         super(throwable);   
	     }   
	     private static String createFriendlyErrMsg(String msgBody)   
	     {   
	         String prefixStr = "抱歉";   
	         String suffixStr = " 請稍後再試或與管理員聯絡";   
	         StringBuffer friendlyErrMsg = new StringBuffer("");   
	         friendlyErrMsg.append(prefixStr);   
	         friendlyErrMsg.append(msgBody);   
	         friendlyErrMsg.append(suffixStr);   
	         return friendlyErrMsg.toString();   
	     }   
}

3,異常處理類
package net.xnzz.util;

import java.io.IOException;
import java.lang.reflect.Method;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.dao.DataAccessException;

/**
 * 由Spring AOP呼叫 輸出異常資訊把程式異常拋向業務異常  
 * @author WANGJIE
 *
 */
public class ExceptionAdvisor implements ThrowsAdvice 
{
	public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable   
	{   
    // 在後臺中輸出錯誤異常異常資訊通過log4j輸出。    
    Logger log = Logger.getLogger(target.getClass());  
    log.info("***********************************************************");   
    log.info("Error happened in class: " + target.getClass().getName());
    log.info("Error happened in method: " + method.getName());   
    for (int i = 0; i < args.length; i++)   
    {   
        log.info("arg[" + i + "]: " + args[i]);   
    }   
    log.info("Exception class: " + ex.getClass().getName());   
    log.info("ex.getMessage():" + ex.getMessage());   
    ex.printStackTrace();   
    log.info("***********************************************************");  
    
    // 在這裡判斷異常根據不同的異常返回錯誤。    
    if (ex.getClass().equals(DataAccessException.class))   
    {   
        ex.printStackTrace();   
        throw new BusinessException("資料庫操作失敗");   
    } 
    else if (ex.getClass().toString().equals(NullPointerException.class.toString()))   
    {   
        ex.printStackTrace();   
        throw new BusinessException("呼叫了未經初始化的物件或者是不存在物件");   
    } 
    else if (ex.getClass().equals(IOException.class))   
    {   
        ex.printStackTrace();   
        throw new BusinessException("IO異常");   
    } 
    else if (ex.getClass().equals(ClassNotFoundException.class))   
    {   
        ex.printStackTrace();   
        throw new BusinessException("指定的類不存在");   
    } 
    else if (ex.getClass().equals(ArithmeticException.class))
    {   
        ex.printStackTrace();   
        throw new BusinessException("數學運算異常");   
    } else if (ex.getClass().equals(ArrayIndexOutOfBoundsException.class))   
    {   
        ex.printStackTrace();   
        throw new BusinessException("陣列下標越界!");   
    } 
    else if (ex.getClass().equals(IllegalArgumentException.class)) 
    {   
        ex.printStackTrace();   
        throw new BusinessException("方法的引數錯誤");   
    } 
    else if (ex.getClass().equals(ClassCastException.class))   
    {   
        ex.printStackTrace();   
        throw new BusinessException("型別強制轉換錯誤");   
    } 
    else if (ex.getClass().equals(SecurityException.class))   
    {   
        ex.printStackTrace();   
        throw new BusinessException("違背安全原則異常");   
    }
    else if (ex.getClass().equals(SQLException.class))   
    {   
        ex.printStackTrace();   
        throw new BusinessException("操作資料庫異常");   
    } 
    else if (ex.getClass().equals(NoSuchMethodError.class))   
    {   
        ex.printStackTrace();   
        throw new BusinessException("方法末找到異常");   
    } 
    else if (ex.getClass().equals(InternalError.class))   
    {   
        ex.printStackTrace();   
        throw new BusinessException("Java虛擬機發生了內部錯誤");   
    } 
    else   
    {   ex.printStackTrace();   
        throw new BusinessException("程式內部錯誤操作失敗" + ex.getMessage());   
    }   

}
}

4,Spring配置檔案新增

<!-- Spring 統一日誌處理   LogInterceptor攔截器 配置 -->      

<bean id="logLnterceptor" class="net.xnzz.util.LogInterceptor"/>   
<!-- Spring 統一異常處理  ExceptionAdvisor配置 -->   
<bean id="exceptionHandler" class="net.xnzz.util.ExceptionAdvisor"></bean>   
<!-- Bean自動代理處理器 配置-->     
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator" >   
 <property name="beanNames">   
	<list>    <!-- 配置需要進行日誌記錄的Service和Dao -->   
		<value>*Dao</value>   
        <!-- 配置所有Service結尾命名的Bean即所有Service層的類都要經過exceptionHandler異常處理類 -->    
        <!--<value>*Service</value>   Service層的Bean ID 命名要以Service結尾 -->   
     </list>   
    </property>   
    <property name="interceptorNames">   
     <list>   
          <value>exceptionHandler</value>   
          <value>logLnterceptor</value>   
          <!--<value>transactionInterceptor</value>-->   
     </list>   
    </property>   
 </bean>