没有梦想,何必远方

自定义注解实现日志记录

package com.hxgd.util;

import java.lang.annotation.*;    

/**  
 *自定义注解 拦截Controller  
【需要设置启动aspectj注解,通知spring使用cglib而不是jdk代理】 
*/    
    
@Target({ElementType.PARAMETER, ElementType.METHOD})    
@Retention(RetentionPolicy.RUNTIME)    
@Documented    
public  @interface SystemControllerLog {    
    // descption 描述方法的实际作用
    String description()  default "";    
}   
package com.hxgd.util;
   
import org.aspectj.lang.JoinPoint;    
import org.aspectj.lang.annotation.*;    
import org.slf4j.Logger;    
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;    
import org.springframework.web.context.request.RequestContextHolder;    
import org.springframework.web.context.request.ServletRequestAttributes;

import com.hxgd.pojo.Logs;
import com.hxgd.pojo.Users;
import com.hxgd.service.LogService;

import javax.annotation.Resource;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpSession;    
import java.lang.reflect.Method;
import java.util.Date;    
/**  
 * 切点类  
 */    
@Aspect    //表示该类为一个切面类
@Component //@component组件扫描,让其 logService能注入进来   
public  class SystemLogAspect {    
    //注入Service用于把日志保存数据库    
    @Resource  
     private LogService logService;
  
    //本地异常日志记录对象    
     private  static  final Logger logger = LoggerFactory.getLogger(SystemLogAspect. class);    
  
    
    //Controller层切点    
    @Pointcut("@annotation(com.bjsxt.util.SystemControllerLog)")    
     public  void controllerAspect() {    
    }    
    
    /**  
     * 前置通知 用于拦截Controller层记录用户的操作  
     *  
     * @param joinPoint 切点  
     */    
    @Before("controllerAspect()")    
     public  void doBefore(JoinPoint joinPoint) {    
    
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();    
        HttpSession session = request.getSession();    
        //读取session中的用户    
        Users user = (Users) session.getAttribute("user");
        //获取用户名
        
        String username = user==null?"null":user.getFullname();
        //请求的IP    
        String ip = request.getRemoteAddr();    
         try {    

            //*========数据库日志=========*//    
            Logs log = new Logs();
         
            log.setAction(getControllerMethodDescription(joinPoint));
            log.setActiontime(new Date(System.currentTimeMillis()));
            log.setUsername(username);
            log.setIp(ip);       
            logService.saveLog(log);
            //System.out.println("=====前置通知结束=====");    
        }  catch (Exception e) {    
            //记录本地异常日志    
            logger.error("====系统抛出前置通知异常====");  
            e.printStackTrace();
            logger.error("异常信息:{}", e.getMessage());    
        }    
    }    
   
    
    /**  
     * 获取注解中对方法的描述信息 用于Controller层注解  
     *  
     * @param joinPoint 切点  
     * @return 方法描述  
     * @throws Exception  
     */    
     public  static String getControllerMethodDescription(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 = "";    
         for (Method method : methods) {    
             if (method.getName().equals(methodName)) {    
                Class[] clazzs = method.getParameterTypes();    
                 if (clazzs.length == arguments.length) {    
                    description = method.getAnnotation(SystemControllerLog. class).description();    
                     break;    
                }    
            }    
        }    
         return description;    
    }    
}    

 

posted @ 2018-03-10 17:48  北极丶光  阅读(5827)  评论(0编辑  收藏  举报