Spring + Aop+注解 集成使用 Log4j,实现异常日志记录

A,首先说,如何配置:

       1,在web.xml中添加代码:

            <!-- log4j的配置相关 -->  

                <context-param>  

                    <param-name>log4jConfigLocation</param-name>  

                    <param-value>classpath:config/log4j/log4j.properties</param-value>  

                </context-param>  

                <context-param>  

                    <param-name>log4jRefreshInterval</param-name>  

                    <param-value>6000000</param-value>  

                </context-param> 

                <listener>  

                    <listener-class>  

                        org.springframework.web.util.Log4jConfigListener  

                    </listener-class>  

                </listener>  

                <!-- end --> 

        2,classpath:config/log4j/log4j.properties配置文件如下:

                

            ### set log levels ###  

            log4j.rootLogger = WARN ,  stdout ,  D ,  E  

              

            ### \u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###  

            log4j.appender.stdout = org.apache.log4j.ConsoleAppender  

            log4j.appender.stdout.Target = System.out  

            log4j.appender.stdout.layout = org.apache.log4j.PatternLayout  

            log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}   [ %p ]  %m%n   

            

            ### \u8F93\u51FA\u5230\u65E5\u5FD7\u6587\u4EF6 ###  

            log4j.appender.D = org.apache.log4j.DailyRollingFileAppender  

            #log4j.appender.D.File = D://WARN_log.log  

            log4j.appender.D.File = /mnt/soft/tomcat/common_logs/tomcat_6082_Warn_log.log

            log4j.appender.D.Append = true

            log4j.appender.D.Encoding=UTF-8

            log4j.appender.D.Threshold = WARN  

            log4j.appender.D.layout = org.apache.log4j.PatternLayout  

            log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %p ]  %m%n  

              

            ### \u4FDD\u5B58\u5F02\u5E38\u4FE1\u606F\u5230\u5355\u72EC\u6587\u4EF6 ###  

            log4j.appender.E = org.apache.log4j.DailyRollingFileAppender  

            #log4j.appender.E.File = D://error_log.log

            log4j.appender.E.File = /mnt/soft/tomcat/common_logs/tomcat_6082_Error_log.log

            log4j.appender.E.Append = true

            log4j.appender.E.Encoding=UTF-8

            log4j.appender.E.Threshold = ERROR

            log4j.appender.E.layout = org.apache.log4j.PatternLayout  

            log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH:mm:ss}   [ %p ]  %m%n 

            

            具体的参数含义,参考:http://blog.csdn.net/azheng270/article/details/2173430/

                


B,其次,如何配合注解和Aop,实现  异常日志记录:

            

            1,自定义注解:

                @Documented

                @Inherited

                @Target({ElementType.PARAMETER, ElementType.METHOD})

                @Retention(RetentionPolicy.RUNTIME)

                public  @interface ServiceExceptionLog {    

                    String description()  default "异常信息";    

                }  

            2,自定义一个切面类,并使用:

                package com.sxb.web.common.aop;

                import org.apache.log4j.Logger;

                import org.aspectj.lang.JoinPoint;  

                import org.aspectj.lang.annotation.*;  

                import org.springframework.stereotype.Component;   

                import com.google.gson.Gson;

                import com.sxb.web.common.interceptor.annotate.ServiceExceptionLog;

                

                import java.lang.reflect.Method;  

                  

                /** 

                 * 切点类 

                 * @author tiangai 

                 * @since 2014-08-05 Pm 20:35 

                 * @version 1.0 

                 */  

                @Aspect  

                @Component  

                public  class ServiceExceptionLogAspect {  

                   

                 //本地异常日志记录对象  

                    private  static  final Logger logger = Logger.getLogger(ServiceExceptionLogAspect.class.getName());  

                  

                    //Service层切点  

                    @Pointcut("execution(* com.sxb.web.v2.wh.service.impl.*.*(..))")

                 public void serviceAspect() {

                 }

                  

                    

                  

                    /** 

                     * 异常通知 用于拦截service层记录异常日志 

                     * 

                     * @param joinPoint 

                     * @param e 

                     * @throws Exception 

                     */  

                     @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")  

                     public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) throws Exception {  

                        

                //     HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();  

                //        HttpSession session = request.getSession();  

                        //获取用户请求方法的参数并序列化为JSON格式字符串    

                        String params = "";    

                         if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {    

                             for ( int i = 0; i < joinPoint.getArgs().length; i++) {    

                                params += new Gson().toJson(joinPoint.getArgs()[i]) + ";";    

                            }    

                        }     

                        StringBuilder bd = new StringBuilder();

                        bd.append("异常方法相关信息:"+getServiceMthodDescription(joinPoint)).append("    ###  ").

                        append("异常代码:"+e.getClass().getName()).append("    ###   ")

                        .append("异常信息:"+e.getMessage()).append("    ###   ")

                        .append("参数:"+params);

                        

                        logger.error(bd.toString());  

                  

                    }  

                    /** 

                     * 获取注解中对方法的描述信息 用于service层注解 

                     * 

                     * @param joinPoint 切点 

                     * @return 方法描述 

                     * @throws Exception 

                     */  

                     public  static String getServiceMthodDescription(JoinPoint joinPoint)  

                             throws Exception {  

                        String targetName = joinPoint.getTarget().getClass().getName();  

                        String methodName = joinPoint.getSignature().getName();  

                        Object[] arguments = joinPoint.getArgs();  

                        Class targetClass = Class.forName(targetName);  

                        Method[] methods = targetClass.getMethods();  

                        String description = "异常类是:"+targetName+" ;异常方法名称:"+methodName+" ;异常描述信息:";  

                         for (Method method : methods) {  

                             if (method.getName().equals(methodName)) {  

                                Class[] clazzs = method.getParameterTypes();  

                                 if (clazzs.length == arguments.length) {  

                                    description += method.getAnnotation(ServiceExceptionLog.class).description();  

                                     break;  

                                }  

                            }  

                        }  

                         return description;  

                    }  

                }  

            3,给一个Service方法添加异常日志记录注解:

                

                        @ServiceExceptionLog(description="--自定义异常描述---")

                 public  void test(String str)     {

                 int aa =12/0;

                 }


你可能感兴趣的:(spring,log4j,+,实现异常日志记录,Aop+注解,集成使用)