自定義注解實現日志記錄


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;    
    }    
}    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM