Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 3512|回复: 0

使用Spring进行统一日志管理 + 统一异常管理

[复制链接]
  • TA的每日心情
    奋斗
    2024-11-24 15:47
  • 签到天数: 804 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726782
    发表于 2021-4-23 13:48:53 | 显示全部楼层 |阅读模式

    统一日志和异常管理配置好后,SSH项目中,代码以往散落的log.info() 和 try..catch..finally 再也不见踪影!

    统一日志异常实现类:

    [java]  view plain  copy
     
    1. package com.pilelot.web.util;  
    2.   
    3. import org.apache.log4j.Logger;  
    4. import org.springframework.aop.ThrowsAdvice;  
    5. import org.springframework.dao.DataAccessException;  
    6.   
    7. import java.io.IOException;  
    8. import java.lang.reflect.Method;  
    9. import java.sql.SQLException;  
    10.   
    11. /** 
    12.  * 由Spring AOP调用 输出异常信息,把程序异常抛向业务异常 
    13.  *  
    14.  * @author Andy Chan 
    15.  * 
    16.  */  
    17. public class ExceptionAdvisor implements ThrowsAdvice  
    18. {  
    19.     public void afterThrowing(Method method, Object[] args, Object target,  
    20.             Exception ex) throws Throwable  
    21.     {  
    22.         // 在后台中输出错误异常异常信息,通过log4j输出。  
    23.         Logger log = Logger.getLogger(target.getClass());  
    24.         log.info("**************************************************************");  
    25.         log.info("Error happened in class: " + target.getClass().getName());  
    26.         log.info("Error happened in method: " + method.getName());  
    27.             for (int i = 0; i < args.length; i++)  
    28.             {  
    29.                 log.info("arg[" + i + "]: " + args);  
    30.             }  
    31.         log.info("Exception class: " + ex.getClass().getName());  
    32.         log.info("ex.getMessage():" + ex.getMessage());  
    33.         ex.printStackTrace();  
    34.         log.info("**************************************************************");  
    35.   
    36.         // 在这里判断异常,根据不同的异常返回错误。  
    37.         if (ex.getClass().equals(DataAccessException.class))  
    38.         {  
    39.             ex.printStackTrace();  
    40.             throw new BusinessException("数据库操作失败!");  
    41.         } else if (ex.getClass().toString().equals(  
    42.                 NullPointerException.class.toString()))  
    43.         {  
    44.             ex.printStackTrace();  
    45.             throw new BusinessException("调用了未经初始化的对象或者是不存在的对象!");  
    46.         } else if (ex.getClass().equals(IOException.class))  
    47.         {  
    48.             ex.printStackTrace();  
    49.             throw new BusinessException("IO异常!");  
    50.         } else if (ex.getClass().equals(ClassNotFoundException.class))  
    51.         {  
    52.             ex.printStackTrace();  
    53.             throw new BusinessException("指定的类不存在!");  
    54.         } else if (ex.getClass().equals(ArithmeticException.class))  
    55.         {  
    56.             ex.printStackTrace();  
    57.             throw new BusinessException("数学运算异常!");  
    58.         } else if (ex.getClass().equals(ArrayIndexOutOfBoundsException.class))  
    59.         {  
    60.             ex.printStackTrace();  
    61.             throw new BusinessException("数组下标越界!");  
    62.         } else if (ex.getClass().equals(IllegalArgumentException.class))  
    63.         {  
    64.             ex.printStackTrace();  
    65.             throw new BusinessException("方法的参数错误!");  
    66.         } else if (ex.getClass().equals(ClassCastException.class))  
    67.         {  
    68.             ex.printStackTrace();  
    69.             throw new BusinessException("类型强制转换错误!");  
    70.         } else if (ex.getClass().equals(SecurityException.class))  
    71.         {  
    72.             ex.printStackTrace();  
    73.             throw new BusinessException("违背安全原则异常!");  
    74.         } else if (ex.getClass().equals(SQLException.class))  
    75.         {  
    76.             ex.printStackTrace();  
    77.             throw new BusinessException("操作数据库异常!");  
    78.         } else if (ex.getClass().equals(NoSuchMethodError.class))  
    79.         {  
    80.             ex.printStackTrace();  
    81.             throw new BusinessException("方法末找到异常!");  
    82.         } else if (ex.getClass().equals(InternalError.class))  
    83.         {  
    84.             ex.printStackTrace();  
    85.             throw new BusinessException("Java虚拟机发生了内部错误");  
    86.         } else  
    87.         {  
    88.             ex.printStackTrace();  
    89.             throw new BusinessException("程序内部错误,操作失败!" + ex.getMessage());  
    90.         }  
    91.     }  
    92. }  


    自定义业务异常处理类 友好提示:

    [java]  view plain  copy
     
    1. package com.pilelot.web.util;  
    2.   
    3. /** 
    4.  * 自定义业务异常处理类    友好提示 
    5.  * @author Andy Chan 
    6.  * 
    7.  */  
    8. public class BusinessException extends RuntimeException  
    9. {  
    10.     private static final long serialVersionUID = 3152616724785436891L;  
    11.   
    12.     public BusinessException(String frdMessage)  
    13.     {  
    14.         super(createFriendlyErrMsg(frdMessage));  
    15.     }  
    16.   
    17.     public BusinessException(Throwable throwable)  
    18.     {  
    19.         super(throwable);  
    20.     }  
    21.   
    22.     public BusinessException(Throwable throwable, String frdMessage)  
    23.     {  
    24.         super(throwable);  
    25.     }  
    26.   
    27.     private static String createFriendlyErrMsg(String msgBody)  
    28.     {  
    29.         String prefixStr = "抱歉,";  
    30.         String suffixStr = " 请稍后再试或与管理员联系!";  
    31.   
    32.         StringBuffer friendlyErrMsg = new StringBuffer("");  
    33.   
    34.         friendlyErrMsg.append(prefixStr);  
    35.   
    36.         friendlyErrMsg.append(msgBody);  
    37.   
    38.         friendlyErrMsg.append(suffixStr);  
    39.   
    40.         return friendlyErrMsg.toString();  
    41.     }  
    42. }  


     

     

    统一日志处理实现类:

    [java]  view plain  copy
     
    1. package com.pilelot.web.util;  
    2.   
    3. import org.aopalliance.intercept.MethodInterceptor;  
    4. import org.aopalliance.intercept.MethodInvocation;  
    5. import org.apache.log4j.Logger;  
    6.   
    7. /** 
    8.  * Spring 统一日志处理实现类 
    9.  * @author Andy Chan 
    10.  *  
    11.  */  
    12. public class LogInterceptor implements MethodInterceptor  
    13. {  
    14.   
    15.     public Object invoke(MethodInvocation invocation) throws Throwable  
    16.     {  
    17.         Logger loger = Logger.getLogger(invocation.getClass());  
    18.   
    19.         loger.info("--Log By Andy Chan -----------------------------------------------------------------------------");  
    20.         loger.info(invocation.getMethod() + ":BEGIN!--(Andy ChanLOG)");// 方法前的操作  
    21.         Object obj = invocation.proceed();// 执行需要Log的方法  
    22.         loger.info(invocation.getMethod() + ":END!--(Andy ChanLOG)");// 方法后的操作  
    23.         loger.info("-------------------------------------------------------------------------------------------------");  
    24.   
    25.         return obj;  
    26.     }  
    27.   
    28. }  

     

    Spring配置文件添加:

     

    [html]  view plain  copy
     
    1. <!-- Spring 统一日志处理   LogInterceptor拦截器 配置 -->     
    2. <bean id="logLnterceptor" class="com.pilelot.web.util.LogInterceptor"/>  
    3. <!-- Spring 统一异常处理  ExceptionAdvisor配置 -->  
    4. <bean id="exceptionHandler" class="com.pilelot.web.util.ExceptionAdvisor"></bean>  
    5.   
    6.     <!-- Bean自动代理处理器 配置-->    
    7. <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator" >  
    8.    <property name="beanNames">  
    9.     <list>    <!-- 配置需要进行日志记录的Service和Dao -->  
    10.         <value>commonDao</value>  
    11.                 <!-- 配置所有Service结尾命名的Bean,即所有Service层的类都要经过exceptionHandler异常处理类 -->   
    12.         <value>*Service</value>  <!-- Service层的Bean ID 命名要以Service结尾 -->  
    13.     </list>  
    14.    </property>  
    15.    <property name="interceptorNames">  
    16.     <list>  
    17.          <value>exceptionHandler</value>  
    18.          <value>logLnterceptor</value>  
    19.          <!--<value>transactionInterceptor</value>-->  
    20.     </list>  
    21.    </property>  
    22. </bean>  
    23. lt;!-- ——————————————————Spring 统一日志处理 + 统一异常处理  配置结束—————————————悲伤的分隔线—————————— -->  




    这样简单三步,就实现了由Spring统一日志+统一异常管理,代码清爽了不少!

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-4 22:05 , Processed in 0.057789 second(s), 27 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表